如何在 nodejs / nextjs api 处理程序中确定 http 与 https
How to determine http vs https in nodejs / nextjs api handler
为了在我的 xml 站点地图和 rss 提要中正确构建我的 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
}
使用上面的代码,但是在 Vercel 上它仍然显示为在 http
上提供服务。我希望它 运行 为 https
。有没有更好的方法来计算 http
与 https
?
作为 Next.js api 路由 运行 在卸载到 http 的代理后面,协议是 http
。
通过将代码更改为以下内容,我能够首先检查代理 运行s 的协议。
const proto = req.headers["x-forwarded-proto"];
然而,这会破坏开发过程中您不在代理后面 运行 的事情,或者以不同的方式部署可能也不涉及代理的解决方案。为了支持这两种用例,我最终得到了以下代码。
const proto =
req.headers["x-forwarded-proto"] || req.connection.encrypted
? "https"
: "http";
只要 x-forwarded-proto
header 不存在 (undefined
),我们就会回到 req.connection.encrypted 来确定我们是否应该在 http
与 https
.
现在它可以在本地主机和 Vercel 部署上运行。
为了在我的 xml 站点地图和 rss 提要中正确构建我的 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
}
使用上面的代码,但是在 Vercel 上它仍然显示为在 http
上提供服务。我希望它 运行 为 https
。有没有更好的方法来计算 http
与 https
?
作为 Next.js api 路由 运行 在卸载到 http 的代理后面,协议是 http
。
通过将代码更改为以下内容,我能够首先检查代理 运行s 的协议。
const proto = req.headers["x-forwarded-proto"];
然而,这会破坏开发过程中您不在代理后面 运行 的事情,或者以不同的方式部署可能也不涉及代理的解决方案。为了支持这两种用例,我最终得到了以下代码。
const proto =
req.headers["x-forwarded-proto"] || req.connection.encrypted
? "https"
: "http";
只要 x-forwarded-proto
header 不存在 (undefined
),我们就会回到 req.connection.encrypted 来确定我们是否应该在 http
与 https
.
现在它可以在本地主机和 Vercel 部署上运行。