Unhandled promise rejection - Error: Can't set headers after they are sent

前提是你 提交于 2021-02-19 05:42:08

问题


I am new to node, and I have a simple situation, where I am posting to an endpoint on a node/express app. The issue is that I get:

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.

The relevant code that I have which is generating this is:

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'
      });
    });
});

and then:

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();
    }
  });
}

I do know that if I remove the res.status(500).json({status: 'error'}); specifically, then the error goes away, but I am not sure if that is proper.

Any clue to what exactly is my error and how to fix?


回答1:


You are trying to send response twice. First when catching the error

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

And then after catch, promise chain continues the normal route until:

  return localAuth.encodeToken(user[0]);

Which fails, because user is undefined and throws an exception.. so error handler is called and you are trying to send response again, but it fails because it has already been sent once

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

console log which error was thrown in the last part, I'm pretty sure it is something like

  TypeError: Cannot read property '0' of undefined


来源:https://stackoverflow.com/questions/42149589/unhandled-promise-rejection-error-cant-set-headers-after-they-are-sent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!