如何在 nodejs / nextjs api 处理程序中确定 http 与 https

Mar*_*rco 7 http-headers node.js next.js

为了在 xml 站点地图和 rss feed 中正确构建我的 url,我想确定该网页当前是通过 http 还是 https 提供服务,因此它也可以在本地开发中使用。

export default function handler(req, res) {
  const host = req.headers.host;
  const proto = req.connection.encrypted ? "https" : "http";

  //construct url for xml sitemaps
}
Run Code Online (Sandbox Code Playgroud)

然而,使用上面的代码,在 Vercel 上它仍然显示为通过 提供服务http。我希望它运行为https. 有没有更好的方法来找出httpvs https

Mar*_*rco 6

由于 Next.js api 路由在代理后面运行,该代理正在卸载到 http,协议是http

通过将代码更改为以下内容,我能够首先检查代理运行的协议。

  const proto = req.headers["x-forwarded-proto"];
Run Code Online (Sandbox Code Playgroud)

然而,这将破坏开发中的情况,即您不在代理后面运行,或者部署可能不涉及代理的解决方案的不同方式。为了支持这两个用例,我最终得到了以下代码。

  const proto =
    req.headers["x-forwarded-proto"] || req.connection.encrypted
      ? "https"
      : "http";
Run Code Online (Sandbox Code Playgroud)

每当x-forwarded-proto标头不存在 ( undefined) 时,我们就会回退到 req.connection.encrypted 来确定是否应该在httpvs上提供服务https

现在它可以在本地主机以及 Vercel 部署上运行。

  • req.connection 已弃用。它说使用 req.socket 代替,但我没有看到加密的参数。 (15认同)