How to programmatically send a 404 response with Express/Node?


I want to simulate a 404 error on my Express/Node server. How can I do that?

5/7/2014 2:20:20 PM

Accepted Answer

Nowadays there's a dedicated status function for this on the response object. Just chain it in somewhere before you call send.

res.status(404)        // HTTP status 404: NotFound
   .send('Not found');
10/15/2014 1:11:36 PM

You don't have to simulate it. The second argument to res.send I believe is the status code. Just pass 404 to that argument.

Let me clarify that: Per the documentation on it seems as though any number passed to res.send() will be interpreted as the status code. So technically you could get away with:


Edit: My bad, I meant res instead of req. It should be called on the response

Edit: As of Express 4, the send(status) method has been deprecated. If you're using Express 4 or later, use: res.sendStatus(404) instead. (Thanks @badcc for the tip in the comments)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow