作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
编辑:
问题正是在身份验证中(实际上它工作正常,但是, token 指的是数据库中的旧用户 ID):
const { email, oldPassword } = req.body;
const user = await User.findByPk(req.userId);
if (email !== user.email) {
const userExists = await User.findOne({ where: { email } });
if (userExists) {
return res.status(400).send({ error: 'User already exists.' });
}
}
可能,在我手动更改数据库后, token 无法识别这一点。 (我也设置了 7 天到期)
Executing (default): SELECT "id", "name", "email", "password_hash", "provider", "created_at" AS "createdAt", "updated_at" AS "updatedAt" FROM "users" AS "User" WHERE "User"."id" = 7;
(node:1616) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'email' of null
at update (C:\Project\src\app\controllers\UserController.js:56:24)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1616) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate
the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1616) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
附:
WHERE "User"."id" = 7;
(在这种情况下,用户数据库中的 ID 将为 = 1)
at update (C:\Project\src\app\controllers\UserController.js:56:24)
UserController 上的这部分代码:
if (email !== user.email) { // <<<---- Here
const userExists = await User.findOne({ where: { email } });
if (userExists) {
return res.status(400).send({ error: 'User already exists.' });
}
}
理解问题:
routes.use(authMiddleware);
(在 ./src/routes.js 中)
import { Router } from 'express';
import UserController from './app/controllers/UserController';
import authMiddleware from './app/middlwares/auth';
const routes = new Router();
routes.use(authMiddleware);
routes.put('/users', UserController.update);
export default routes;
.src/app/controllers/UserController.js
import User from '../models/User';
class UserController {
async update(req, res) {
const { email, oldPassword } = req.body;
const user = await User.findByPk(req.userId);
if (email !== user.email) {
const userExists = await User.findOne({ where: { email } });
if (userExists) {
return res.status(400).send({ error: 'User already exists.' });
}
}
if (oldPassword && !(await user.checkPassword(oldPassword))) {
return res.status(401).json({ error: 'Password does not match' });
}
const { id, name, provider } = await user.update(req.body);
return res.json({
id,
name,
email,
provider,
});
}
}
export default new UserController();
./src/app/models/User.js
import Sequelize, { Model } from 'sequelize';
import bcrypt from 'bcryptjs';
class User extends Model {
static init(sequelize) {
super.init(
{
name: Sequelize.STRING,
email: Sequelize.STRING,
password: Sequelize.VIRTUAL,
password_hash: Sequelize.STRING,
provider: Sequelize.BOOLEAN,
},
{
sequelize,
}
);
this.addHook('beforeSave', async (user) => {
if (user.password) {
user.password_hash = await bcrypt.hash(user.password, 8);
}
});
return this;
}
checkPassword(password) {
return bcrypt.compare(password, this.password_hash);
}
}
export default User;
./src/database/migrations/number-create-users.js
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('users', {
id: {
type: Sequelize.INTEGER,
allowNulll: false,
autoIncrement: true,
primaryKey: true,
},
name: {
type: Sequelize.STRING,
allowNulll: false,
},
email: {
type: Sequelize.STRING,
allowNulll: false,
unique: true,
},
password_hash: {
type: Sequelize.STRING,
allowNulll: false,
},
provider: {
type: Sequelize.BOOLEAN,
defaultValue: false,
allowNulll: false,
},
created_at: {
type: Sequelize.DATE,
allowNulll: false,
},
updated_at: {
type: Sequelize.DATE,
allowNulll: false,
},
});
},
down: async (queryInterface) => {
await queryInterface.dropTable('users');
},
};
HTTP/PUT JSON 数据:
{
"name": "user000",
"email": "email000@domain.com.br",
"oldPassword": "password000",
"password": "123456",
"confirmPassword": "123456"
}
考虑到用户已经通过身份验证。
最佳答案
问题可能是以下查询未找到用户。因此 user
可能是 undefined
。你确定这条线是正确的吗?
const user = await User.findByPk(req.userId);
并且
userId
不应该出现在请求正文中或
params
中? IE。:
const user = await User.findByPk(req.params.userId);
如果用户 id 在参数中,我认为您还需要将
route
更新为:
routes.put('/users/:userId', UserController.update);
此外,我认为将异步内容包装到 try catch 块中是一种很好的做法。像这样:
try {
const user = await User.findByPk(req.params.userId);
} catch (err) {
console.log(err)
}
关于node.js - Node /更新/API/序列化 : UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'email' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66934844/
我是一名优秀的程序员,十分优秀!