I want to simulate a 404 error on my Express/Node server. How can I do that?
- 
                    7How would "simulated" differ from a "real" one? – Jon Hanna Dec 05 '11 at 23:34
6 Answers
Since Express 4.0, there's a dedicated sendStatus function:
res.sendStatus(404);
If you're using an earlier version of Express, use the status function instead.
res.status(404).send('Not found');
 
    
    - 300,895
- 165
- 679
- 742
- 
                    9
- 
                    27Worth noting that on it's own `res.status(404);` wont send a response AFAIK. It needs to either be chained with something, e.g. `res.status(404).end();` or your second example, or it needs to be followed by e.g. `res.end();`, `res.send('Not found');` – UpTheCreek Oct 15 '14 at 12:03
- 
                    1@UpTheCreek, I'll remove the first example from the code to avoid the potential for that confusion. – Drew Noakes Oct 15 '14 at 13:10
- 
                    1
- 
                    
Updated Answer for Express 4.x
Rather than using res.send(404) as in old versions of Express, the new method is:
res.sendStatus(404);
Express will send a very basic 404 response with "Not Found" text:
HTTP/1.1 404 Not Found
X-Powered-By: Express
Vary: Origin
Content-Type: text/plain; charset=utf-8
Content-Length: 9
ETag: W/"9-nR6tc+Z4+i9RpwqTOwvwFw"
Date: Fri, 23 Oct 2015 20:08:19 GMT
Connection: keep-alive
Not Found
 
    
    - 159,648
- 54
- 349
- 530
- 
                    2I'm pretty sure it's just `res.status(404)` not `res.sendStatus(404)`. – Jake Wilson Dec 24 '15 at 05:54
- 
                    6`res.sendStatus(404)` is correct. It is equivalent to `res.status(404).send()` – Justin Johnson Feb 19 '16 at 20:16
- 
                    3Yep `res.sendStatus(404); ` is equivalent to `res.status(404).send('Not Found')` – Rick Sep 10 '16 at 15:51
- 
                    
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:
res.send(404);
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)
 
    
    - 56,800
- 10
- 90
- 93
- 
                    1You could also send a message with the 404: `res.send(404, "Could not find ID "+id)` – Pylinux May 05 '13 at 07:35
- 
                    Sending a status code directly is deprecated in 4.x and will probably be removed at some point. Best to stick with `.status(404).send('Not found')` – Matt Fletcher Oct 22 '14 at 08:50
- 
                    3For Express 4: "express deprecated res.send(status): Use res.sendStatus(status) instead" – badcc Jan 03 '16 at 03:36
According to the site I'll post below, it's all how you set up your server. One example they show is this:
var http = require("http");
var url = require("url");
function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    route(handle, pathname, response);
  }
  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}
exports.start = start;
and their route function:
function route(handle, pathname, response) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
    handle[pathname](response);
  } else {
    console.log("No request handler found for " + pathname);
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not found");
    response.end();
  }
}
exports.route = route;
This is one way. http://www.nodebeginner.org/
From another site, they create a page and then load it. This might be more of what you're looking for.
fs.readFile('www/404.html', function(error2, data) {
            response.writeHead(404, {'content-type': 'text/html'});
            response.end(data);
        });
 
    
    - 11,042
- 3
- 36
- 41
 
    
    - 3,525
- 2
- 20
- 18
From the Express site, define a NotFound exception and throw it whenever you want to have a 404 page OR redirect to /404 in the below case:
function NotFound(msg){
  this.name = 'NotFound';
  Error.call(this, msg);
  Error.captureStackTrace(this, arguments.callee);
}
NotFound.prototype.__proto__ = Error.prototype;
app.get('/404', function(req, res){
  throw new NotFound;
});
app.get('/500', function(req, res){
  throw new Error('keyboard cat!');
});
 
    
    - 26,870
- 12
- 93
- 104
 
    
    - 62,577
- 16
- 155
- 122
- 
                    1This example code is no longer at the link you reference. Might this apply to an earlier version of express? – Drew Noakes May 08 '13 at 10:51
- 
                    It actually stil applies to the existing code, all you have to do is to use the error handle middleware to catch the error. Ex: `app.use(function(err, res, res, next) { if (err.message.indexOf('NotFound') !== -1) { res.status(400).send('Not found dude'); }; /* else .. etc */ });` – alessioalex May 09 '13 at 18:59
IMO the nicest way is to use the next() function:
router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}
Then the error is handled by your error handler and you can style the error nicely using HTML.
 
    
    - 5,375
- 2
- 45
- 54
- 
                    Yeah, I agree, in a node/express context using the middleware is far more consistent. – Leven Oct 02 '20 at 09:37
 
    