node.js - 需要理解为什么expressjs重定向到index.html

标签 node.js express

我有以下服务器文件,使用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/

相关文章:

javascript - 在nodejs中断言模块使用?

objective-c - 创建 OSX 应用程序来运行基于终端的服务器

javascript - 如何使用node js在前端显示modgodb中存储的图像URL路径

javascript - 将未定义的 JSON 转换为新的 JSON 对象

javascript - 如何仅使用 uglifyjs 将多个文件缩小为一个文件?

javascript - 在node.js中构建socket.io/express应用程序时我需要http吗?

python - 通过 Websockets 在 Nodejs 和 Python 之间通信

node.js - Express.js REST API 无法在 Heroku 上运行

Node.js TLS "TypeError: Cannot read property ' indexOf' 未定义”

javascript - Model.remove() 根本不起作用