【问题标题】:Unhandled promise rejection - Error: Can't set headers after they are sent未处理的承诺拒绝 - 错误:发送后无法设置标头
【发布时间】:2017-02-10 00:40:48
【问题描述】:

我是 node 新手,我有一个简单的情况,我在 node/express 应用程序上发布到端点。问题是我得到了:

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'});,错误就会消失,但我不确定是否这是正确的。

我的错误到底是什么以及如何解决的任何线索?

【问题讨论】:

  • 我忘了说,这个错误信息是在用户名、密码不够长或者用户名已经存在于数据库中的时候出现的。

标签: node.js express knex.js


【解决方案1】:

您尝试发送响应两次。首先在捕获错误时

  res.status(410).json({
    status: err.message
  });

然后在 catch 之后,promise 链继续正常的路线,直到:

  return localAuth.encodeToken(user[0]);

失败,因为用户未定义并引发异常..因此调用错误处理程序并且您尝试再次发送响应,但它失败了,因为它已经发送过一次

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

控制台记录最后一部分抛出的错误,我很确定它类似于

  TypeError: Cannot read property '0' of undefined

【讨论】:

    猜你喜欢
    • 2017-09-08
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 2021-06-03
    • 2016-09-02
    • 2018-11-07
    相关资源
    最近更新 更多