2017-08-06 112 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