Search code examples
javascriptnode.jsexpresshttp-redirectexpress-handlebars

NodeJS/ExpressJS doesn't redirect to the homepage


I am working on a shopping cart application in nodejs/expressjs. I am having some problems with redirecting back to the '/' page after submitting the credentials of the user at the sign up. I didn't find any articles related to this problem. I am also using CSURF protection. The problem is if I press the submit button, from

localhost:3000/user/signup/

goes to

localhost:3000/user/signup?email=something&password=somepassword&_csrf=QQdMG3kT-kOPAucSUipAlAUQaRSoLJrWlMQc

And it doesn't go back to the homepage. (localhost:3000)

This is the code from the index.js file:

var express = require('express');
var router = express.Router();
var Product = require('../models/product');
var csrf = require('csurf');

var csrfProtection = csrf();

/* GET home page. */
router.use(csrfProtection);

router.get('/', function(req, res, next) {
  res.setHeader("Content-Type", "text/html");
  Product.find(function(err, docs){
    var productChunks = [];
    chunkSize = 2;
    for(var i = 0; i < docs.length; i+= chunkSize){
        productChunks.push(docs.slice(i, i + chunkSize));
    }
    res.render('shop/index', { title: 'Humble', products: docs });
  });

});
router.get('/user/signup', function(req, res, next){
  res.render('user/signup', {csrfToken: req.csrfToken()});
});

router.post('/user/signup', function(req, res, next){
    res.redirect('/');
});
module.exports = router;

This is the code from the signup.hbs file:

    <h1 class = "subtitlu"><b>Sign UP!</b></h1>
    Validation Errors
    <form action = "/user/signup" metod = "post" 
style = 
"box-shadow: 5px 10px 18px #888888;
font-family:Helvetica-Medium;
font-size:25px;
padding:25px;
margin-bottom:30px;
margin-top:30px;
overflow:hidden;">
        <div class="form-group">
            <label for="email">E-mail</label>
            <input type="text" id="email" name="email" class="form-control">
        </div>
        <div class="form-group">
            <label for="password">Parola</label>
            <input type="password" id="password" name="password" class = "form-control">
        </div>
        <input type = "hidden" name = "_csrf" value = {{ csrfToken }}>
        <button type = "submit" class = "btn btn-primary" style="background-color:rgb(0, 219, 66);  position: relative;
  float: right;">Create an account!</button>
    </form>

Solution

  • you have a typo in your form: metod = "post" updating metod to method should do the job

    redirecting is not working because there's no POST request to /user/signup