未处理的承诺拒绝 – 错误:发送后无法设置标头

我是新来的节点,我有一个简单的情况,我张贴到节点/快递应用程序的端点。 问题是我得到:

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]); 

哪个失败,因为用户是未定义的,并引发exception..所以error handling程序被调用,你试图再次发送响应,但它失败,因为它已经发送一次

  res.status(500).json({ status: 'error' }); 

控制台日志哪个错误是在最后一部分抛出,我很确定这是类似的东西

  TypeError: Cannot read property '0' of undefined