无法读取null + passport.js的属性“body”

我试图在Node / Express / Sequelize应用程序中实现passport.js。 我试图尽可能忠实于官方文档和Scotch.io教程 ,目前在我的脚手架上有以下相关的代码段:

app.js

const express = require('express'); const http = require('http'); const https = require('https'); const sequelize = require('sequelize'); const db = require('./config/sequelize'); const config = require('./config/config'); const passport = require('./config/passport'); const app = express(); const port = 3000; app.use(passport.initialize()); app.use(passport.session()); app.set('view engine', 'ejs'); app.listen(port); app.post('/signup', passport.authenticate('local', function(req, res, next, err){ if (err) { console.log(err); } res.json(req.body); })); 

./config/passport.js

 const db = require('./sequelize'); const passport = require('passport'), LocalStrategy = require('passport-local').Strategy; passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(user, done) { db.User.findById(id, function(err, user) { done(err, user); }); }); passport.use('local', new LocalStrategy({ usernameField : 'email', passwordField : 'password', passReqToCallback : true }, function(email, password, done){ process.nextTick(function() { db.User.findOne({ email : 'local.email' }, function(err, user) { if (err) return done(err); if (user) { return done(null, false, req.flash('signupMessage', 'That email is already taken.')); } else { db.User.create({ username: 'local.email', password: 'local.password' }); } }); }); } )); module.exports = passport; 

./views/signup.ejs

 <!-- LOGIN FORM --> <form action="/signup" method="post"> <div class="form-group"> <label>Email</label> <input type="text" name="username"> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password"> </div> <button type="submit">Signup</button> </form> 

有了这个实现,我启动应用程序,input电子邮件地址和密码注册./views/signup.ejs,并得到以下错误:

 TypeError: Cannot read property 'body' of null at C:\Users\Adam\Desktop\repos\chinese-democracy\app.js:45:15 at allFailed (C:\Users\Adam\Desktop\repos\chinese-democracy\node_modules\passport\lib\middleware\authenticate.js:94:18) at attempt (C:\Users\Adam\Desktop\repos\chinese-democracy\node_modules\passport\lib\middleware\authenticate.js:167:28) ... 

这表明req.body被返回为null,并且我怀疑它与在./config/passport.js中定义deserializeUser和serializeUser函数的方式有关,但是如何获得详细的错误输出确定究竟是什么原因? 另外,我已经使用Sequelize数据库完成了完整的CRUD检查,所以我省略了这个文件,但是如果你们中的任何人认为这个文件可以解决这个问题,那么它将作为一个编辑提供。

       

网上收集的解决方案 "无法读取null + passport.js的属性“body”"

请在你的app.js试试这个:

 app.post('/signup', passport.authenticate('local'), function(req, res, next, err){ //^ close // If this function gets called, authentication was successful. res.redirect('/users/' + req.user.username); }); 

如果您需要自定义callback:

 app.post('/signup', function(req, res, next){ passport.authenticate('local', function(err, user, info) { //Your code here })(req, res, next); }); 

有关更多详细信息,请参阅http://passportjs.org/docs/authenticate