2013-10-10 20 views
4

我試圖設置一個全局函數,在每個頁面加載時調用,而不管它在我的位置網站。根據Express的API,我已經使用Node.js Express - app.all(「*」,func)在訪問根域時沒有被調用

app.all("*", doSomething); 

在每個頁面加載時調用函數doSomething,但它不能完全工作。除了基本域的頁面加載外(例如http://domain.com/pageA將調用該函數,但http://domain.com不會),該函數會在每個頁面加載時觸發。有誰知道我做錯了什麼?

謝謝!

+0

柏拉圖的回答是最有可能的解決您的問題。但如果不是這樣,那麼對於像這些發佈相關代碼的情況來說明問題是必要的,以便我們提供適當的解決方案。如果您的問題未解決,請張貼更完整的路線定義示例。 –

回答

2

我敢打賭,你放置

app.get('/', fn) 

上述

app.all("*", doSomething); 

記住Express將在他們註冊的順序,如果你要到的東西發送響應

1

執行中間件功能對每個請求運行一些代碼,您不需要使用路由器。

只需將路由器上面的一箇中間件,它會在每次請求被稱爲:

app.use(function(req, res, next){ 
    //whatever you put here will be executed 
    //on each request 

    next(); // BE SURE TO CALL next() !! 
}); 

希望這有助於

1

凡在鏈app.all(「*」)?如果它畢竟是其他路線,它可能不會被調用。

app.post("/something",function(req,res,next){ ...dothings.... res.send(200); }); 

app.all('*',function(req,res) { ...this NEVER gets called. No next and res already sent }); 

除非你打算讓它成爲最後一個,在這種情況下,你必須確保在前面的路由中調用next()。例如:

app.post("/something",function(req,res,next){ ...dothings.... next();}); 

app.all('*',function(req,res) { ...this gets called }); 

另外,什麼是doSomething?你確定它沒有被叫?

4

我知道這是一箇舊的,但仍然可能對某人有用。

我想這個問題可能是:

app.use(express.static(path.join(__dirname, 'public'))); 

var router = express.Router(); 

router.use(function (req, res, next) { 
    console.log("middleware"); 
    next(); 
}); 

router.get('/', function(req, res) { 
    console.log('root'); 
}); 
router.get('/anything', function(req, res) { 
    console.log('any other path'); 
}); 

任何路徑在哪裏被調用中間件,但/

這是因爲express.static根據預設public/index.html/

爲了解決它將參數添加到靜態中間件:

app.use(express.static(path.join(__dirname, 'public'), { 
    index: false 
})); 
0

我也有這個問題,我發現你的doSomething函數有多少參數可能是一個因素。

function doSomething(req, res, next) { 
    console.log('this will work'); 
} 

而:

function doSomething(req, res, next, myOwnArgument) { 
    console.log('this will never work'); 
} 
+1

我相信這是因爲Express將4元處理程序解釋爲具有簽名'函數句柄(err,req,res,next)的錯誤處理程序(',並且我認爲如果您執行'next(err)',則會調用整個錯誤處理鏈)來自之前的處理程序或中間件 – Plato

相關問題