Giuan Adauto Giuan Adauto - 1 month ago 32
Node.js Question

Getting a Bad request on passport on Node

I'm trying to run some basic tests with passport on Node, and when I try to access the route localhost:3000/login I get a Bad request 400. Here is the code:

var express = require('express');
var app = express();
var jwt = require('jsonwebtoken');
var passport = require('passport');

var LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
function(username, password, done) {
var user = {
username: "name",
password: "password123"
}

return done(null, user);
}
));




app.post('/login',
passport.authenticate('local', {session: false}),
function(req, res) {
req.user.name = "Giuan";
res.send(req.user.name);
//res.redirect('/users/' + req.user.username);
});

app.listen(3000, ()=>{
console.log('Running on port 3000');
})

Answer

Try this:

var express = require('express');
var app = express();
var jwt = require('jsonwebtoken');
var passport = require('passport');
var bodyParser = require('body-parser');

//if you are getting the info (username and password) through the body 
//of the http request you need to use body-parser
app.use(bodyParser());

var LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
    function(username, password, done) {
        var user = {
            username: "name",
            password: "password123"
        }

    return done(null, user); 
    }
));


app.use(passport.initialize());

app.post('/login',
  passport.authenticate('local', {session: false}),
  function(req, res) {
    req.user.name = "Giuan";
    res.send(req.user.name);
    //res.redirect('/users/' + req.user.username);
  });

app.listen(3000, ()=>{
    console.log('Running on port 3000');
})
Comments