Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The reason of ERR_HTTP_HEADERS_SENT error in Express.js middleware

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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 })
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading