我有以下服务器文件,使用express:
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
时执行
尽管这是我所希望的行为,但我不确定为什么会这样?
我的根目录中没有“test.html”页面。
另一件事是,index.html 确实加载了其他脚本,所以我期望
app.get('*', function(){...})
对于此类获取请求也执行,因为它应该是包罗万象的,但事实并非如此。
app.use('/', router)
是否意味着任何具有单个字符“/”的路由都应该由 Router 实例处理(只要不是静态文件)?所以“http:localhost:8080”被解释为“http://localhost:8080/”?
如果有任何解释,我将不胜感激。
最佳答案
这一行-
app.use(express.static(__dirname + "/"));
将首先运行。它将发现 index.html
存在并静态提供该文件。
关于node.js - 需要理解为什么expressjs重定向到index.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37670101/