无法使用JWT读取Express上未定义的属性“用户名”

时间:2019-03-21 09:34:43

标签: javascript node.js express jwt

使用Mongodb在 Express js上实现基于 JWT 的登录注册时,当我尝试匹配给定输入的用户来匹配数据库用户名时,出现此错误:

  

TypeError:无法读取未定义的属性“用户名”

这是我的代码:

app.js

const express = require('express');
const path = require('path');
const app = express();
const  jwt  =  require('jsonwebtoken');
const  bcrypt  =  require('bcrypt');
const mongoose = require('mongoose');
const StudentModel = require('./studentmodel');
const SECRET_KEY = "secretkey23456";

const port = process.env.PORT || 3002;
//mongoose coonection
// body Parser Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.post('/register', (req, res) => {

const student = new StudentModel();
let salt = bcrypt.genSaltSync(10);
 student.username  =  req.body.username;
  student.name  =  req.body.name;
  student.email  =  req.body.email;
  student.password  =  bcrypt.hashSync(req.body.password, salt);

 student.save((err, user) => {
    if (err) return  res.status(500).send('Server error!'); 
        console.log(user);
        const  expiresIn  =  24  *  60  *  60;
        const  accessToken  =  jwt.sign({ id:  user.id }, SECRET_KEY, 
         {
            expiresIn:  expiresIn
        });
        res.status(200).send({ "user":  user, "access_token":  
         accessToken, "expires_in":  expiresIn          
        });

       });
    });
 });
  app.get('/', (req, res) => {
  res.render('index');
 });

app.post('/login', (req, res) => {

const username = req.body.username;
const password = req.body.password;
const student = StudentModel.findOne({ username});
if(!student) {
    return res.json('not found');
}
const isValid =  bcrypt.compareSync(password, student.password);
if (student && !isValid) {
    return  res.json(' found');
}

});

app.listen(port, () => console.log(`Server started on port ${port}`));

注册工作正常,但是当我使用登录路径只是为了检查用户名时,出现此错误。我不确定为什么会这样

1 个答案:

答案 0 :(得分:1)

您的代码没有正文解析器软件包-https://expressjs.com/en/4x/api.html#app.post.method。如果在node_modules / packages下不存在,请使用npm install body-parser --save-https://www.npmjs.com/package/body-parser安装。

// ...code
const SECRET_KEY = "secretkey23456";
const bodyParser = require('body-parser');

const port = process.env.PORT || 3002;
// mongoose coonection
// body Parser Middleware
// app.use(express.json()); --> Incorrect
app.use(bodyParser.json()); 
// app.use(express.urlencoded({ extended: true })); --> Incorrect
app.use(bodyParser.urlencoded({ extended: true }));