【问题标题】:Suppress automatic routing to index.html禁止自动路由到 index.html
【发布时间】:2017-12-22 13:42:38
【问题描述】:

我已经使用 Node & Express 设置了一个服务器。所有路由都有效,除了 GET /。它始终显示 index.html(也在公共文件夹中),而不是显示我发送的文件。如果我将 index.html 重命名为其他名称或将其删除,我的 GET / 路由确实有效。

const publicPath = path.join(__dirname, '../public');

app.use(express.static(publicPath));

app.get('/', (req, res) => {
    res.sendFile(publicPath + '/login-register.html');
});

有没有办法抑制 index.html 的自动渲染?

编辑:可能有用的是注意我没有收到任何错误,无论是在我的控制台还是 Chrome 开发工具中。

【问题讨论】:

    标签: javascript express routing


    【解决方案1】:

    发生这种情况是因为 static 中间件匹配 / 路由,因为您在目录中有一个 index.html 文件并将该文件发送到浏览器。第二个中间件函数永远不会运行,因为 / 路由已经匹配。如果您切换中间件函数声明的顺序,它应该会按照您期望的方式工作。

    app.get('/', (req, res) => {
      res.sendFile(publicPath + '/login-register.html');
    });
    
    app.use(express.static(publicPath));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 2012-07-22
      • 1970-01-01
      相关资源
      最近更新 更多