未处理的承诺拒绝 - 错误:发送后无法设置标头
问题描述:
我是新来的节点,我有一个简单的情况,我在某个节点/快速应用的端点上发布消息。问题是,我得到:未处理的承诺拒绝 - 错误:发送后无法设置标头
POST /api/v2/user 500 25.378 ms - 54
(node:19024) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Can't set headers after they are sent.
(node:19024) 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.
相关的代码,我有它产生是这样的:
router.post('/', (req, res, next) => {
return authHelpers.createUser(req, res)
.then((user) => {
return localAuth.encodeToken(user[0]);
})
.then((token) => {
res.status(201).json({
status: 'success',
message: 'User Created',
token: token
});
})
.catch((err) => {
res.status(500).json({
status: 'error'
});
});
});
然后:
function createUser(req, res) {
return handleErrors(req)
.then(() => {
const salt = bcrypt.genSaltSync();
const hash = bcrypt.hashSync(req.body.password, salt);
return knex('users')
.insert({
email: req.body.email,
first_name: req.body.first_name,
last_name: req.body.last_name,
username: req.body.username,
password: hash
})
.returning('*');
})
.catch((err) => {
res.status(410).json({
status: err.message
});
});
}
function handleErrors(req) {
return new Promise((resolve, reject) => {
if (req.body.username.length < 6) {
reject({
message: 'Username must be longer than 6 characters'
});
} else if (req.body.password.length < 6) {
reject({
message: 'Password must be longer than 6 characters'
});
} else {
resolve();
}
});
}
我知道,如果我删除res.status(500).json({status:'error'});具体而言,那么错误消失,但我不知道这是否正确。
任何线索到底是什么是我的错误,以及如何解决?
答
您正尝试发送回复两次。捕捉错误
res.status(410).json({
status: err.message
});
再搭上后首当,承诺继续链,直到正常路线:
return localAuth.encodeToken(user[0]);
哪个失败,因为用户是不确定的,并抛出一个异常..所以调用错误处理程序而你正试图再次发送响应,而是因为它已经被一次该错误是在最后抛出
res.status(500).json({
status: 'error'
});
控制台日志发送失败的话,我敢河畔e它就像
TypeError: Cannot read property '0' of undefined
我忘了提及,当用户名,密码不够长或用户名已经存在于数据库中时出现此错误消息。 –