Express服务器没有收听url请求并返回/ always

时间:2017-12-12 17:48:45

标签: node.js express routing

我有以下快速服务器设置:

const express = require('express');
    const path = require('path');
    const app = express();

    app.use(express.static(path.join(__dirname, 'build')));

    app.get('/', function (req, res) {
        console.log('/*');
        res.sendFile(path.join(__dirname, 'build', 'index.html'));
    });

    app.get('/test', function (req, res) {
        console.log('test');
        //res.sendFile(path.join(__dirname, 'build', 'index.html'));
    });

    app.listen(9000);

每当我点击localhost:9000 / test时,它仍然会占用路线'/'。 我尝试在静态声明之前放置app.get代码,但我认为这没有任何区别。知道为什么会这样吗?

2 个答案:

答案 0 :(得分:0)

您现有的代码很好。它应该工作。

我认为您之前的索引路由为app.get('/*', function (req, res){而不是app.get('/', function (req, res) {,这就是它捕获所有请求的原因。

答案 1 :(得分:0)

/test路由处理程序中,您必须使用res.end()来终止请求 - 响应周期,如下所示:

app.get('/test', function (req, res) {
    console.log('test');
    res.end();
});

否则页面将永远不会刷新显示第一页(路线/)

希望这有帮助