在登录表格中使用护照时收到不良请求

时间:2015-08-11 06:28:15

标签: node.js express passport-local

我正在尝试使用nodejs中的护照本地会话创建用户登录[.ejs文件]表单。我的问题是,当我点击提交按钮时,我一直收到错误的请求,任何人都可以检查我的代码并帮助我

这是我的nodejs代码:

要求:

var express = require('express');   
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var cookieParser = require('cookie-parser')
var expressSession = require('express-session');
var mongodb = require('mongodb');
var mongoose = require('mongoose');
var app = express();
var MongoClient = mongodb.MongoClient;
app.use(expressSession({
    secret: 'secret'
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.set('view engine', 'ejs');

护照:

var user = mongoose.model('val', Schema);
passport.use(new LocalStrategy({
        passReqToCallback: true
    },
    function (firstName, password12, done) {
        console.log("entered Function");
        user.findOne({
                firstName: firstName
            },
            function (err, firstName) {
                if (err) {
                    return done(err);
                }
                if (!firstName) {
                    console.log('User Not Found  ' + firstName);
                }
                if (!isValidPassword(firstName, password12)) {
                    console.log('Invalid Password');
                } else {
                    console.log('correct');
                    return done(null, firstName);
                }
            }
        );
    }));

登录页面:

app.get('/login', function (req, res) {
    res.render('login');
});
app.post('/login', passport.authenticate('local'), function (req, res){
    var userInfo = req.body;
});

2 个答案:

答案 0 :(得分:1)

我相信你发布了部分Nodejs文件代码?您在

调用的身份验证函数的代码在哪里
passport.serializeUser(function (user, done) {
    done(user.Id); // the user id that you have in the session
});

passport.deserializeUser(function (id, done) {
    done({id: Id}); // generally this is done against user database as validation
});

除了authenticate方法,还需要passport.serializeUser和passport.deserializeUser方法。 Passport调用这两个函数,它们是必需的。

这是演示代码。编写自己的代码,将其作为参考

REM writing to file:
>file.txt echo 1234567
REM reading from file:
<file.txt set /p "var="
echo %var%

答案 1 :(得分:0)

passReqToCallback: true

如果您使用此功能,请将 req 添加到代码中。下一行应该是:

function (req, firstName, password12, done) {

你的邮政路由器必须是这样的:

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });