2017-08-06 89 views
0

注意不显示的console.log消息:我是很新的表达express.js路由时

var express = require('express'); 
var app = express(); 

app.get('/', function(req, res) { 
    res.send('id: ' + req.params.id + ' and name: ' + req.params.name); 
}); 
var things = require('./things/things.js'); 

//both index.js and things.js should be in same directory 
app.use('/things', things); 
//Simple request time logger 
app.use('/',function(req, res, next){ 
    console.log("A new request received at " + Date.now()); 

    //This function call is very important. It tells that more processing is 
    //required for the current request and is in the next middleware 
    //function/route handler. 
    next(); 
}); 

app.listen(3000); 

我正在学习有关中间件功能,我试图表现出的console.log消息,当我去到localhost :3000,但没有任何东西显示在我的控制台中,我在这里错过了什么?

回答

3

问题在于Express按照声明的顺序将请求传递给中间件和路由处理程序。如果其中任何一个能够处理请求(通过发回响应),则稍后声明的任何其他匹配的中间件或路由处理程序将不会被调用。

这就是你的情况发生了什么,你的中间件被宣布为路由处理程序。

试试你的中间件移动到前:

app.use('/',function(req, res, next){ 
    console.log("A new request received at " + Date.now()); 
    next(); 
}); 

app.get('/', function(req, res) { 
    res.send('id: ' + req.params.id + ' and name: ' + req.params.name); 
}); 

var things = require('./things/things.js'); 

app.use('/things', things); 
1

首先,您需要检查文件结构。如果index.js和things.js在同一个目录中,那么你需要的功能,需要改变var things = require('./things.js');

下一步,验证您正在寻找在正确的地方,console.log()消息将出现在终端窗口,加载快速服务器,而不是在Web浏览器的控制台中。

+0

啊,我不知道它会在终端,而不是浏览器控制台显示出来,这是为什么? – Snorlax

+0

Express运行在您的服务器上运行的node.js中,而不是在用户浏览器上运行。在你的情况下,服务器只是你的电脑,但它仍然适用。 – harshpatel991