1
我有以下的服務器上的文件,使用快遞:需要理解爲什麼expressjs被重定向到index.html的
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
app.listen(port);
console.log('Listening on port: ' + port);
// get an instance of router
var router = express.Router();
app.use('/', router);
app.use(express.static(__dirname + "/"));
// route middle-ware that will happen on every request
router.use(function(req, res, next) {
// log each request to the console
console.log(req.method, req.url + " logging all requests");
// continue doing what we were doing and go to the route
next();
});
// home page route for port 8080, gets executed when entering localhost:8080
// and redirects to index.html (correctly and as expected)
router.get('/', function(req, res) {
console.log("routing from route")
res.redirect('index.html');
});
// This gets executed when my url is: http://localhost:8080/test
// and redirects to index.html (the questions is why!? I thought
// all the requests to root route would be caught by the router instance
app.get('*', function(req, res){
console.log('redirecting to index.html');
res.redirect('/index.html');
});
看看上面的代碼,我的意見,我不明白爲什麼
app.get('*', function(){...})
當URL爲
localhost:8080/index.html
但在URL爲
localhost:8080/test
時,
不會被執行即使這是我所希望的行爲,但我不確定爲什麼這個行爲KS?
我沒有在根目錄中的「test.html」頁面。 的另一件事,在做的index.html加載其他腳本,所以我預計
app.get('*', function(){...})
得到這樣的get請求執行過,因爲它應該是包羅萬象的,但事實並非如此。
app.use('/', router)
是否意味着任何具有單個字符「/」的路由應由Router實例處理(只要不是靜態文件)?所以「http:localhost:8080」被解釋爲「http://localhost:8080/」?
我將不勝感激任何解釋。
謝謝你的迴應。我對第二個問題的假設是否正確:「app.use('/',router)是否意味着任何具有單個字符」/「的路由應由Router實例處理(只要不是靜態文件) http:localhost:8080「被解釋爲」http:// localhost:8080 /「?」 – Sean12