Passport.js:无法读取undefined(Node)的属性'username'

时间:2017-09-19 03:59:15

标签: javascript node.js passport.js

我正在尝试实施passport-local,但在使用Postman进行测试时,我一直收到此错误:Cannot read property 'username' of undefined

这是我的模型User.js

const mongoose = require('mongoose');
const {Schema} = mongoose;
const passportLocalMongoose = require('passport-local-mongoose');

const User = new Schema({
  username: String,
	email: String,
  password: String,
  firstName: String,
  lastName: String
});

User.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', User);

路线:routes/authRoutes.js

const express = require('express');
const passport = require('passport');
const User = require('../models/User.js');

module.exports = app => {
  // POST to /register
  app.post('/api/register', (req, res) => {
    // Create a user object to save, using values from incoming JSON
    const newUser = new User({
      username: req.body.username,
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      email: req.body.email,
    });

    // Save, via passport's "register" method, the user
    User.register(newUser, req.body.password, (err, user) => {
      // If there's a problem, send back a JSON object with the error
      if (err) {
        return res.send(JSON.stringify({ error: err }));
      }
      // Otherwise, for now, send back a JSON object with the new user's info
      return res.send(JSON.stringify(user));
    });
  });
}

index.js

const express = require('express');
const mongoose = require('mongoose');
const passportLocalMongoose = require('passport-local-mongoose');
const keys = require('./config/keys');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const MongoStore = require('connect-mongo')(session);

mongoose.connect(keys.mongoURI);

const app = express();

app.use(require('express-session')({
  secret: 'secretsecret',
  resave: false,
  saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());


require('./routes/authRoutes')(app);

// Configure Passport
const User = require('./models/User');
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

require('./routes/authRoutes')(app);

const PORT = process.env.PORT || 5000;
app.listen(PORT);

我的package.json

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": "8.1.1",
    "npm": "5.0.3"
  },
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "connect-mongo": "^1.3.2",
    "express": "^4.15.4",
    "express-session": "^1.15.5",
    "mongoose": "^4.11.11",
    "passport": "^0.4.0",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^4.2.1"
  }
}

我已经检查了其他类似的问题,但他们的解决方案不是我的解决方案,大多数都没有初始化Passport。

edit:邮差记录: POST http://localhost:5000/api/register { "username": "Test", "email": "testing@test.com", "password": "password", "firstName": "Testt", "lastName": "Teststs" }

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>TypeError: Cannot read property &#39;username&#39; of undefined
            <br> &nbsp; &nbsp;at app.post (server/routes/authRoutes.js:10:25)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (server/node_modules/express/lib/router/layer.js:95:5)
            <br> &nbsp; &nbsp;at next (server/node_modules/express/lib/router/route.js:137:13)
            <br> &nbsp; &nbsp;at Route.dispatch (server/node_modules/express/lib/router/route.js:112:3)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (server/node_modules/express/lib/router/layer.js:95:5)
            <br> &nbsp; &nbsp;at /server/node_modules/express/lib/router/index.js:281:22
            <br> &nbsp; &nbsp;at Function.process_params (/server/node_modules/express/lib/router/index.js:335:12)
            <br> &nbsp; &nbsp;at next (/server/node_modules/express/lib/router/index.js:275:10)
            <br> &nbsp; &nbsp;at SessionStrategy.strategy.pass (/server/node_modules/passport/lib/middleware/authenticate.js:338:9)
            <br> &nbsp; &nbsp;at SessionStrategy.authenticate (/server/node_modules/passport/lib/strategies/session.js:75:10)
            <br> &nbsp; &nbsp;at attempt (/server/node_modules/passport/lib/middleware/authenticate.js:361:16)
            <br> &nbsp; &nbsp;at authenticate (/server/node_modules/passport/lib/middleware/authenticate.js:362:7)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (/server/node_modules/express/lib/router/layer.js:95:5)
            <br> &nbsp; &nbsp;at trim_prefix (/server/node_modules/express/lib/router/index.js:317:13)
            <br> &nbsp; &nbsp;at /server/node_modules/express/lib/router/index.js:284:7
            <br> &nbsp; &nbsp;at Function.process_params (/server/node_modules/express/lib/router/index.js:335:12)
            <br> &nbsp; &nbsp;at next (/server/node_modules/express/lib/router/index.js:275:10)
            <br> &nbsp; &nbsp;at initialize (/server/node_modules/passport/lib/middleware/initialize.js:53:5)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (/server/node_modules/express/lib/router/layer.js:95:5)
            <br> &nbsp; &nbsp;at trim_prefix (/server/node_modules/express/lib/router/index.js:317:13)
            <br> &nbsp; &nbsp;at /server/node_modules/express/lib/router/index.js:284:7
            <br> &nbsp; &nbsp;at Function.process_params (/server/node_modules/express/lib/router/index.js:335:12)
        </pre>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

你能告诉我们邮递员脚本的身体吗?并确保使用Postman发送POST请求。

编辑:一切似乎都很好。 我认为您需要安装bodyParser并将其用作中间件。

$ npm install --save body-parser
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       
app.use(bodyParser.urlencoded({     
  extended: true
})); 

此处有更多详情:How to retrieve POST query parameters?