我有一个 next.js 13 应用程序,想要添加一个 API 端点/api/getIP。
该route.js文件位于/app/api/getIP/route.js.
最小可复制代码: https ://github.com/Nusab19/nextjs-test/tree/main/app
我尝试了几种方法,但没有一种有效。我尝试使用request-ip获取 ip 但它返回了null。
这是我的代码:
import { NextResponse } from "next/server";
import requestIp from "request-ip";
export async function GET(req) {
const detectedIp = requestIp.getClientIp(req);
const data = {
ok: true,
ip: detectedIp,
userAgent: req.headers.get("user-agent"),
};
return new NextResponse(JSON.stringify(data, null, 2));
}
Run Code Online (Sandbox Code Playgroud)
当我访问时我收到这样的回复:
{
"ok": true,
"ip": null,
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}
Run Code Online (Sandbox Code Playgroud)