Anthony Webb
Anthony Webb

Reputation: 1351

properly handle a 404 in expressjs

A little baffled at how to best handle 404 cases in my app. Here is a gist of a very basic example.

//******************************
// BUILD THE HTTP SERVER
//******************************
var express = require('express');
var app = express.createServer();

app.get('/login', function(req, res){
  console.log("hit the login");
  res.send('you hit the login');
});

app.get('*', function(req, res){
  console.log("got a 404");
  res.send('what???', 404);
});

app.listen(8081);
console.log('Server started on port: 8081');

If I fire up the server and hit the index of the server "/" I properly get the 404 message, HOWEVER, in the logs are 2 "got a 404" log entries on the console... odd.

So if I hit the "/login" page I do get the proper page, and corresponding message to the console, BUT, I ALSO get the 404 message to the console too?

Is this the expected behavior? I am using the latest 2.5.4 express on 4.11 but have tried it on other versions of node with the same results.

I dont really like the fact that my 404 route gets called on every single request, I must be doing something wrong.

Upvotes: 0

Views: 2054

Answers (1)

Juicy Scripter
Juicy Scripter

Reputation: 25918

This is probably due to fact that browser trying to get also favicon for your page.

Just use express.favicon() creating your server:

express.createServer(
  express.favicon()    
);

You may also want to use logger to discover thing like this, it's really useful middleware.

Upvotes: 3

Related Questions