无法读取属性' body'未定义

时间:2019-11-26 21:17:46

标签: javascript node.js express

我正在尝试将护照逻辑放入控制器文件中,但问题是,当我将逻辑放入控制器中时,它告诉我“无法读取未定义的属性'body'”,但是当我将代码移至索引时,所有路由都会路由正确

index.js / controller,问题出在“ postLogin”中

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


module.exports = {
  async postRegister(req, res, next) {

      const newUser = new User({
        username: req.body.username,
        email: req.body.email,
        image: req.body.image

      })

      await User.register( newUser , req.body.password);
      res.redirect('/');
    },
  postLogin(req, res, next) {
    passport.authenticate('local', { successRedirect: '/' ,failureRedirect: '/login' })();
  }
}

index.js / routes

const express = require('express');
const router = express.Router();

const { postRegister, postLogin } = require('../controllers/index');
const { errorHandler } = require('../middleware/index');
/* GET home page. */
router.get('/', (req, res, next) => {
  res.render('index', { title: 'Surf Shop - Home' });
});

/* User routs */

//Get register
router.get('/register', (req, res, next) => {res.send('/register')});

//POST register
router.post('/register', errorHandler(postRegister));

//Get login
router.get('/login', (req, res, next) => { res.send('GET /Login') });

//POST login
router.post('/login', postLogin);

module.exports = router;

图片邮递员

enter image description here

1 个答案:

答案 0 :(得分:2)

括号是否故意放在

passport.authenticate('local', { successRedirect: '/' ,failureRedirect: '/login' })() <----

是否未传递参数?

router.post('/login', postLogin);

成为:

router.post('/login', () => { 
    postLogin(req, res, next) 
});

正确解决:

很有帮助,但此处未传递参数

passport.authenticate('local', { successRedirect: '/' ,failureRedirect: '/login' })(here)

所以变成

`passport.authenticate('local', { successRedirect: '/' ,failureRedirect: '/login' })(req, res, next)`