2017-06-22 73 views
0

我有一個關於app.get() Express的問題。只要路徑末尾有.html,函數似乎就不會被調用。在下面的代碼片段中,如果我嘗試去/random/example,但是當我去/index.html時,"test"被寫入控制檯。那麼當我進入主頁時,如何讓它調用函數呢? (我以「/」作爲嘗試的路徑,它並不能工作。)Node.js express app.get()奇怪的行爲

app.use(express.static("public")) 

app.get('/index.html',function(req,res){ 
    console.log("test"); 
}) 

app.get('/random/example',function(req,res){ 
    console.log("test"); 
}) 
+0

您是否在某處定義了'app.static'? – GilZ

+0

我已將您的問題中的堆棧片段轉換爲代碼塊。例如,Stack Snippets可以在代碼片段窗口中運行(例如,在瀏覽器上)。僅適用於服務器端的代碼不應該放在Stack Snippet中。 –

+0

也許你的index.html(像大多數靜態資源一樣)緩存在瀏覽器中,然後沒有從服務器明確請求 –

回答

0

你沒有看到"test"/index.html,因爲這個過程是你由靜態文件處理被處理。

如果你想讓你的代碼叫做有靜態處理,你需要在設置靜態處理之前定義你的路由。您的路線,然後有效地中間件,並可以調用next傳授給處理的下一層,這將是靜態的處理之前做處理:

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

// Set this up first 
app.get('/index.html',function(req,res, next){ 
    console.log("test - /index.html"); 
    next(); // <== Let next handler (in our case, static) handle it 
}); 

app.get('/random/example',function(req,res){ 
    console.log("test /random/example"); 
}); 

// Now define static handling 
app.use(express.static("public")); 

app.listen(3000, function() { 
    console.log('Example app listening on port 3000!') 
}); 

這在get一個鏈接到Middleware callback function examples提及。

注意:如果您只想將index.html傳送到瀏覽器,則無需這樣做。如果您希望在將請求交給靜態文件處理之前進行請求,那麼您只需執行此操作。

+0

謝謝,這非常有幫助。 – Torstein97