为了在我的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
。
通过将代码更改为以下内容,我可以首先检查代理运行的是什么协议。
const proto = req.headers["x-forwarded-proto"];
然而,这将破坏开发中的东西,当你没有运行在代理之后,或者以不同的方式部署解决方案,也可能不涉及代理。为了支持这两个用例,我最终编写了以下代码:
const proto =
req.headers["x-forwarded-proto"] || req.connection.encrypted
? "https"
: "http";
当x-forwarded-proto
报头不存在(undefined
)时,我们退回到req.connection.encrypted来确定我们是否应该在http
或https
上服务。
现在它可以在本地主机以及Vercel部署上工作。
我的解决方案:
export const getServerSideProps: GetServerSideProps = async (context: any) => {
// Fetch data from external API
const reqUrl = context.req.headers["referer"];
const url = new URL(reqUrl);
console.log('====================================');
console.log(url.protocol); // http
console.log('====================================');
// const res = await fetch(`${origin}/api/projets`)
// const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}