I want to simulate a 404 error on my Express/Node server. How can I do that?
Nowadays there's a dedicated
status function for this on the response object. Just chain it in somewhere before you call
res.status(404) // HTTP status 404: NotFound .send('Not found');
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 expressjs.org 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)