我正在尝试通过id查找用户,但是我收到此错误
(node:16316) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
我尝试使用findByPk和findById,但它不会接受我的值,如下所示。从我读过的书中,人们说这与bodyparser有关,但是我不确定是否已将其安装并放置在此文件中
const express = require('express');
const users = express.Router();
const cors = require('cors');
const moment = require('moment');
const jwt = require('jsonwebtoken');
const auth = require('../middleware/auth');
const bcrypt = require('bcrypt');
const Sequelize = require('sequelize');
var bodyParser = require('body-parser');
const User = require('../models/User');
const config = require('config');
// const secret = 'dassdfdd';
users.use(
bodyParser.urlencoded({
extended: true
})
);
users.use(bodyParser.json());
users.use(cors());
users.get('/getUser', auth, async function(req, res) {
const users = await User.findByPk({ user: req.user.id });
if (!users) {
return res.status(404).send('Cannot find');
}
console.log(users);
res.status(200).json(users);
});
module.exports = users;
用户模型
const Sequelize = require('sequelize');
const db = require('../database/db.js');
module.exports = db.sequelize.define(
'users',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
first_name: {
type: Sequelize.STRING,
required: true,
unique: true,
lowercase: true
},
last_name: {
type: Sequelize.STRING,
required: true,
unique: true,
lowercase: true
},
email: {
type: Sequelize.STRING,
required: true,
unique: true,
lowercase: true
},
password: {
type: Sequelize.STRING,
required: true
},
createdAt: {
type: Sequelize.DATE,
field: 'createdAt'
},
updatedAt: {
type: Sequelize.DATE,
field: 'updatedAt'
}
},
{
timestamps: false
}
);
验证用于受保护路由的中间件文件
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports = (req, res, next) => {
let token = req.headers['x-access-token'] || req.headers['authorization']; // Express headers are auto converted to lowercase
if (token.startsWith('Bearer ')) {
// Remove Bearer from string
token = token.slice(7, token.length);
}
const options = {
expiresIn: '2d'
// issuer: 'https://scotch.io'
};
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secret, options, function(err, decoded) {
if (err) {
return res
.status(401)
.json({ error: true, message: 'Unauthorized access.' });
}
req.user = decoded;
next();
});
} else {
// if there is no token
// return an error
return res.status(403).send({
error: true,
message: 'No token provided.'
});
}
};