0

I have a quite standard line of code to send a status and a json, but Express keeps returning the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, pointing it to this line: res.status(201).json(result)

Claiming the error is resulted by the .json(result) part.

I've checked and eliminated anything looking like another res.send() in the code, so there's no double res:s. Checked the other stackoverflow-questions, all seemed to boil down to there being a double res.send of some sort.

blogRouter.post('/', async (req, res) => {
      const decryptToken = jwt.verify(req.token, process.env.SECRET)
      const user = await User.findById(decryptToken.id)
      const body = req.body
      const blog = new Blog({ title: body.title, author: body.author, url: body.url, likes: body.likes, user: user.id })
      const result = await blog.save()
      user.blogs = user.blogs.concat(result._id)
      await user.save()
      res.status(201).json(result)
  })
ruja
  • 3
  • 2
  • You cannot write to the header after any part of the body has been written. So if you've done something to the body, you cant set the status to 201. Do you do anything else to the res object before this? https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client This answer is comprehensive. – Cal Irvine Jun 18 '19 at 14:15
  • No, this is everything that's done to the res-object, so nothing before res.status – ruja Jun 18 '19 at 18:45

0 Answers0