Home > other >  Why do we need to add .end() to a response?
Why do we need to add .end() to a response?

Time:07-03

Currently building a RESTful API with express on my web server, and some routes like the delete route for a document with mongoose ex. await Note.findByIdAndRemove(request.params.id) response.status(204).end() send response statuses with end()

Why do I need to add the .end()? What in these cases, and why cant one just send response.status(204)

With some responses that return json, the response.status(201).json works fine

CodePudding user response:

Only certain methods with Express or the http interface will send the response. Some methods such as .status() or .append() or .cookie() only set state on the outgoing response that will be used when the response is actually sent - they don't actually send the response itself. So, when using those methods, you have to follow them with some method that actually sends the response such as .end().

In your specific example of:

response.status(204)

You can use the Express version that actually sends the response:

response.sendStatus(204)

If you choose to use .status() instead, then from the Express documentation, you have to follow it with some other method that causes the response to be sent. Here are examples from the Express documentation for .status():

res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')

Since all three of these other methods will cause the response to be sent and when the response goes out, it will pick up the previously set status.

  • Related