我正在向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
以下是一些你应该查看的相关链接:
- Vercel文档关于检索客户端IP地址,
- Node.js关于
req.socket.localAddress
的文档
根据这个,你应该可以用下面的代码得到它:
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",
},
};
}