【问题标题】:Code inside get not running after using express.static使用 express.static 后内部代码无法运行
【发布时间】:2017-08-22 08:50:39
【问题描述】:

这是我的 nodejs express 设置:

var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('*', function (req, res) {
  res.sendfile('public/index.html')
});

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!');
});


module.exports = app;

我发现当它使用时:

app.use(express.static('public'));

get 内部没有任何东西运行:

app.get('*', function (req, res) { // 这里没有运行 res.sendfile('public/index.html') });

ps:我想在 get 中重定向(http -> https)。

【问题讨论】:

  • 你在尝试什么路线?而且,它在您的public 目录中有匹配的文件吗? express.static() 只会在找到匹配文件时处理。我不知道您问题的 http -> https 部分是关于什么的,因为您在任何地方都没有显示任何代码。
  • public 是我的 webpack 生成的文件夹。我确信它完全匹配。我需要在 app.get 回调函数中做一些事情,例如:重定向 http -> https。但是 get 函数内部的代码永远不会运行。为什么..?
  • 正如我已经说过的,如果express.static() 匹配路由,那么它将处理它,并且在它之后的任何请求处理程序都不会看到请求。如果您想在express.static() 行之前运行某些东西,那么您可能需要在express.static() 行之前有一个app.use() 中间件处理程序。您没有显示任何与 https 有关的代码,所以我仍然不知道那是什么。
  • 好的,我明白了。。我需要在 express.static() 之前添加“app.use()”中间件,这个中间件可以将 http 重定向到 https.. 对!?

标签: node.js http express server


【解决方案1】:

如果您想将所有 http 请求重定向到 https,则插入一个 app.use() 中间件作为第一个请求处理程序,并将重定向逻辑重定向到 https。 Express 按照您定义的顺序处理请求处理程序,并且您希望在您的 express.static() 中间件之前先处理此中间件。

当然,您需要将所有其他请求处理程序放在 https 服务器上(而不是放在 http 服务器上),以便 https 服务器可以在重定向后处理您的 URL(您的代码没有显示)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2022-01-14
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多