can't register, it keep saying bad Request

I am using passport, node and express in my project. I keep getting this error when i try to register: Bad Request

I am not sure what the problem is. If I delete the authentication, it works perfectly but when I add it, it gives me the same error so I think there's a problem that I can't find. Thank you. I really appreciate it!!!

  const express = require('express');
    const bodyParser =require("body-parser");
    const passport=require("passport");
    const mongoose= require("mongoose");
    const passportLocalMongoose = require('passport-local-mongoose');
    const session = require("session");
    const expressSession =require("express-session");
    const app = express();
    const LocalStrategy = require('passport-local').Strategy
    const Schema= mongoose.Schema;


    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(express.static("public"));
    app.set('view engine', 'ejs');

    mongoose.connect('mongodb://localhost:27017/userDB2', {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true});

    const userSchema= new mongoose.Schema({ 
        email:String, 
        password:String
    })
    userSchema.plugin(passportLocalMongoose)

    const User= mongoose.model("User",userSchema);

    passport.use(User.createStrategy());

    passport.serializeUser(User.serializeUser());
    passport.deserializeUser(User.deserializeUser())


    app.get('/', (req, res) => {
        res.render('index');
    });
    app.get('/login', (req, res) => {
        res.render('login');
    });

    app.get("/register",(req,res)=>
    {
        res.render("register");
    })
    app.get('/message', (req, res) => {

        if(req.isAuthenticated())
        {
            res.redirect("/message")
        }
        else 
        {
            res.redirect("/register")
        }

    });

    app.post("/register",(req,res)=>
    {
        const email= req.body.email;
        const password= req.body.password;
        User.register({username:email}, password, function(err, user) {
      if (err) { 
          console.log("err")
          res.redirect("/register")
      }
      else 
      { 
          passport.authenticate("local")(req,res, function() 
          {

          res.redirect("/message")

          })

      }
        })
    })



    app.listen('4000', (req, res) => {
        console.log('working and refreshin...')
    });

1 answer

  • answered 2020-06-02 10:23 Sven.hig

    I think you are messing this important lines for passport to work sessions

    app.use(session({secret: 'secret'}))
    app.use(passport.initialize());
    app.use(passport.session());