1
我是新來的節點,我有一個簡單的情況,我在某個節點/快速應用的端點上發佈消息。問題是,我得到:未處理的承諾拒絕 - 錯誤:發送後無法設置標頭
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'});具體而言,那麼錯誤消失,但我不知道這是否正確。
任何線索到底是什麼是我的錯誤,以及如何解決?
我忘了提及,當用戶名,密碼不夠長或用戶名已經存在於數據庫中時出現此錯誤消息。 –