Home > Mobile >  The reason of ERR_HTTP_HEADERS_SENT error in Express.js middleware
The reason of ERR_HTTP_HEADERS_SENT error in Express.js middleware

Time:07-20

I have created middleware to validate fields in body, here is how it looks like:

Front-end route:

router.post('/s-i', async (req, res) => {
  try {
    const { data } = await api.post('/sign-in', req.body)

    res.cookie("_rt", data._rt, { httpOnly: true, secure: false })
    delete data._rt

    return res.json(data)
  } catch (e) {
    // Here is error
    return res.status(e.response.status).json(e.response.data)
  }
});

Route (back-end):

router.post('/sign-in', v(['email', 'password', 'twoFa', 'phone']), wrapAsync(userController.signIn));

Middleware:

exports.v = fields => {
  return (req, res, next) => {
    fields.forEach(field => {
      if (req.body[field]) {
        const result = require(`./validators/${field}`)(req.body[field])
        if (!result)
          return res.status(400).json({ message: 'bad-request', status: 400 })
      }
    })
    next()
  }
}

In the place where comment is placed I can see this error, actually, everything works find, and if there is wrong field in body front will receive 400 status code, but in back-end terminal I still have this error and can't get why.

The problem is I still keep getting this ERR_HTTP_HEADERS_SENT error. I know the reason of this problem - for example - if you are trying do res.send({}) twice, but I don't really see the reason of problem in this case.

CodePudding user response:

The return res.status(400)... statement returns only from the inner function fields.forEach(field => {...}), but you must return from the middleware function, otherwise the next() will invoke subsequent middlewares after the .json output, leading to the observed error.

You can achieve this by replacing fields.forEach(field => {...}) with

for (var field of fields) {
  if (req.body[field]) {
    const result = require(`./validators/${field}`)(req.body[field])
    if (!result)
      return res.status(400).json({ message: 'bad-request', status: 400 })
  }
}
  • Related