需要了解为什么expressjs重定向到index.html

时间:2016-06-07 03:43:39

标签: 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但在网址为localhost:8080/test时执行
虽然这是我希望的行为,但我不确定为什么会这样?
我在根目录中没有“test.html”页面。 另外一件事,index.html确实加载了其他脚本,所以我期待

app.get('*', function(){...})    

也可以执行此类获取请求,因为它应该是全部捕获,但事实并非如此。

app.use('/', router)是否意味着任何具有单个字符“/”的路由应由路由器实例处理(只要不是静态文件)?所以“http:localhost:8080”被解释为“http://localhost:8080/”?

我将不胜感激。

1 个答案:

答案 0 :(得分:1)

这一行 -

app.use(express.static(__dirname + "/"));

将首先运行。它会看到index.html存在并静态提供该文件。