在expressjs中正确处理404

时间:2022-11-29 16:14:09

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

有点困惑于如何在我的应用程序中最好地处理404个案例。这是一个非常基本的例子的要点。

//******************************
// 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.

如果我启动服务器并点击服务器的索引“/”我正确地获取404消息,但是,在日志中2“在控制台上有一个404”的日志条目...奇怪。

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?

所以,如果我点击“/ login”页面,我会得到正确的页面,并向控制台发送相应的消息,但是,我也得到了404消息到控制台?

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.

这是预期的行为吗?我在4.11上使用最新的2.5.4 express,但是在其他版本的节点上尝试了相同的结果。

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

我真的不喜欢我的404路由在每个请求都被调用的事实,我一定是做错了。

1 个解决方案

#1


3  

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

这可能是因为浏览器试图为您的页面获取favicon。

Just use express.favicon() creating your server:

只需使用express.favicon()创建您的服务器:

express.createServer(
  express.favicon()    
);

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

您可能还想使用logger来发现这样的东西,它是非常有用的中间件。

#1


3  

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

这可能是因为浏览器试图为您的页面获取favicon。

Just use express.favicon() creating your server:

只需使用express.favicon()创建您的服务器:

express.createServer(
  express.favicon()    
);

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

您可能还想使用logger来发现这样的东西,它是非常有用的中间件。