我正在向 Vercel 边缘函数发出 GET 请求,但似乎无法在 API 函数内获取 IP 地址。
所有这些标题值都显示
undefined
export const config = {
runtime: "edge",
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<APIResponseData>
) {
console.log("realip", req.headers["x-real-ip"]);
console.log("forwardedfor", req.headers["x-forwarded-for"]);
console.log("vercelforwardedfor", req.headers["x-vercel-forwarded-for"]);
console.log("x-vercel-ip-country", req.headers["x-vercel-ip-country"]);
return new Response(
JSON.stringify({
data: {
data: "ok",
},
}),
{
status: 200,
headers: {
"content-type": "application/json"
},
}
);
}
这有效:
边缘功能:
import { ipAddress } from "@vercel/edge";
export const config = {
runtime: "edge",
};
export default function (request: Request) {
const ip = ipAddress(request) || "unknown";
return;
new Response(
`<h1>Your IP is
${ip}
</h1>`,
{
headers: {
"content-type": "text/html",
},
}
);
}
边缘中间件:
import { ipAddress } from "@vercel/edge";
export const config = {
runtime: "edge",
};
export default function (request: Request) {
const ip = ipAddress(request) || "unknown";
return;
new Response(
`<h1>Your IP is
${ip}
</h1>`,
{
headers: {
"content-type": "text/html",
},
}
);
}
参考:https://vercel.com/docs/concepts/functions/edge-functions/vercel-edge-package#ipaddress
以下是您应该检查的一些相关链接:
根据这个,你应该可以通过以下代码获取它:
export const config = {
runtime: "edge",
};
export default async function handler(
req,
res
) {
console.log({ip: req.socket.localAddress});
return {
status: 200,
body: JSON.stringify({
data: "ok",
}),
headers: {
"content-type": "application/json",
},
};
}