0

I'm creating this web application using Nodejs,hbs, Express and Mysql.

So I have implemented a form and set the form action to '/auth/addawish' where it will go through an authentication by not allowing everyone to add a new entry

addawish.hbs file

{{>header}}

<div class="container mt-4">
  <div class="card">
    <div class="card-header">Make a Wish</div>
    <div class="card-body">


      <form action="/auth/addawish" method="POST">
        <div class="mb-3">
          <label for="name" class="form-label">Wish Name</label>
          <input type="text" class="form-control" id="name" name="wishname">
        </div>
        <div class="mb-3">
          <label for="price" class="form-label">Wish price</label>
          <input type="text" class="form-control" id="price" name="wishprice">
        </div>
        <input type="hidden" name="userid" value="{{user.id}}">

        <button type="submit" class="btn btn-success">Submit</button>
      </form>
    </div>
  </div>
  {{#if message}}
  <h4 class="alert alert-danger mt-4">{{message}}</h4>
  {{/if}}
</div>

{{>footer}} 

Then in route file i have added the following

router.get('/addawish', authController.isLoggedIn , (req,res) => {
  if(req.user){
    res.render("addawish", {
      user:req.user
    });
  }else {
    res.redirect('/login');
  }
 
});

isLoggedIn method implemented as follows

exports.isLoggedIn = async (req, res, next) => {
  // console.log(req.cookies);
  if (req.cookies.jwt) {
    try {
      //Verify the token
      const decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET);
      console.log(decoded);

      //Check if the user still exists
      db.query('SELECT * FROM users WHERE id =?', [decoded.id], (error, result) => {
        console.log(result);

        if (!result) {
          return next();
        }
        req.user = result[0];
        return next();
      });
    } catch (error) {
      console.log(error);
      return next();
    }
  } else {
    next();
  }
}

and if url sees auth, it will go to the separate route as follows

controllers/auth.js

const express = require('express');
const router = express.Router();
const authController = require('../controllers/auth');



router.post('/register', authController.register);
router.post('/login',authController.login);  
router.get('/logout',authController.logout);
router.post('/addawish',authController.saveawish);

module.exports = router;

Finally following is the saveawish method

//saving a wish
exports.saveawish = async (req, res) => {
  console.log(req.body);
  const wishname = req.body.wishname;
  const wishprice = req.body.wishprice;
  const wishby = req.body.userid;


  const now = new Date();
  const wishposteddate = now.getFullYear() + '-' +
    (now.getMonth() + 1).toString().padStart(2, '0') + '-' +
    now.getDate().toString().padStart(2, '0') + ' ' +
    now.getHours().toString().padStart(2, '0') + ':' +
    now.getMinutes().toString().padStart(2, '0') + ':' +
    now.getSeconds().toString().padStart(2, '0');

  db.query('INSERT INTO wishes SET ?', { wish_name: wishname, wish_price: wishprice, wish_posted_date: wishposteddate, wish_by: wishby }, (error, results) => {
    if (error) {
      console.log(error);
    } else {
      return res.render('addawish', {
        message: 'Wish added'
      });
    }
  });

}

In above saveawish if i use this piece of code,

 return res.render('addawish', {
        message: 'Wish added'
      });

it will sending the route to http://localhost:3000/auth/addawish i want it to be redirect back to http://localhost:3000/addawish. For that i tried return res.redirect('/addawish') but then i won't be able to send the message to the frontend.

Is there a better way to redirect it back to http://localhost:3000/addawish and still manage to send the message successfully

AVI
  • 5,516
  • 5
  • 29
  • 38

0 Answers0