我有一个 Next.js 项目,我正在使用 next/headers 以编程方式返回对我的 API 的请求的基本 URL。
const baseUrl = () => {
const protocol = process?.env.NODE_ENV === "development" ? "http" : "https";
const host = headers().get("host");
const baseUrl = `${protocol}://${host}`;
return baseUrl;
}
export const fetchUser = async () => {
try {
console.log(`${baseUrl()}/api/getUser`);
const response = await fetch(`${baseUrl()}/api/aps/getUser`, { method: 'GET', headers: headers() });
const data = await response.json();
return data.data;
} catch (error) {
console.error("Error fetching user:", error);
}
};
这在我的机器上运行良好,
headers().get("host")
按预期返回localhost:3000
。
我有另一位开发人员也在本地运行该项目,但他获得的不是
localhost:3000
,而是值 [::1]:59982
,其中末尾的 5 位端口每次都会发生变化。
这个值从哪里来?
似乎与 Node 版本有关。我在 v 16.20.2 上没有遇到此问题,但在 v 18.18.2 和 v 20.9.0 上却出现了。