2016-04-21 79 views
1

在快遞的NodeJS模塊,指定的路徑 「/」 將趕上等 「/」, 「LIB/main.js」, 「圖像/ icon.gif」 等快車的NodeJS根路徑

var app = require('express') 
app.use('/', authenticate); 
多個HTTP請求

在上面的例子中,如果作爲authenticate隨後

var authenticate = function(request, response, next) { 
    console.log("=> path = " + request.path); 
    next() 
} 

然後定義你會看到

=> path =/
=> path = /lib/main.js 
=> path = /images/icon.gif 

誰能告訴我如何defin快遞「app.use」中只有「/」的e路徑?

+1

'app.get('/')'? – hassansin

回答

0

如果您嘗試公開靜態文件,通常人們將它們放在名爲public/的文件夾中。 express有一個名爲static的內置中間件來處理對此文件夾的所有請求。現在

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

app.use(express.static('./public')); 
app.use('/', authenticate); 

app.get('/home', function(req, res) { 
    res.send('Hello World'); 
}); 

如果你把在公共圖像/ CSS/JavaScript文件,您可以訪問他們,如果public/是根目錄

<script src="http://localhost/lib/main.js"></script> 
+0

順便說一句,你聲明你的中間件和路由事宜。 – aray12

0

據我瞭解,你需要做的是,如果什麼你有'/'&'/ abc'你需要單獨捕捉它。第一

​​

手段,註冊/ ABC中間件,然後執行/中間件:

這將這樣的伎倆。

此解決方案也存在問題。這裏我們只聲明/ abc。所以當用戶調用未註冊的路徑時,它會在這裏打開。 您可以使用請求對象中的originalUrl屬性來確定它的/ only或還有其他內容。這裏是這個文檔:http://expressjs.com/en/api.html#req.originalUrl

if(req.originalUrl !== '/'){ 
    res.status(404).send('Sorry, we cannot find that!'); 
} 
else{ 
    /*Do your stuff*/ 
} 
+0

感謝您的評論。但這不是問題。使用你的例子驗證方法將被調用,無論路徑,這是我的問題。 – iwan