为什么没有指定子域时 HTTP -> HTTPS 重定向在 nodejs 中失败?

Why does HTTP -> HTTPS redirect fail in nodejs when no subdomain is specified?

我是 运行 Heroku 上的 nodejs 网络应用程序,我想将所有通过 http 访问的用户重定向到 https 并使用相应的 URL。

我大部分时间都在使用它,但是如果没有指定子域,用户将被重定向到主页。知道这里发生了什么吗?

节点重路由中间件:

app.enable('trust proxy');
  app.use((req, res, next) => {
    if (req.get('X-Forwarded-Proto') !== 'https') {
      res.redirect(`https://${req.headers.host + req.url}`);
    } else {
      next();
    }
  });

作品: http://www.example.com/page redirects to https://www.example.com/page

失败: http://example.com/page redirects to https://www.example.com

因为req.url是属性继承自Node.JS的http模块,不一定包含原来的URL。 Express.JS 文档也说明了这一点,https://expressjs.com/en/api.html#req.originalUrl

如果您想保留原来的url,您应该使用正确的属性,即originalUrl

app.enable('trust proxy');
  app.use((req, res, next) => {
    if (req.get('X-Forwarded-Proto') !== 'https') {
      res.redirect(`https://${req.headers.host + req.originalUrl}`);
    } else {
      next();
    }
  });