小编Nus*_*b19的帖子

如何在 Next.js 13 中获取客户端的 IP 地址?

我有一个 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)

ip-address next.js next.js13

5
推荐指数
1
解决办法
3385
查看次数

标签 统计

ip-address ×1

next.js ×1

next.js13 ×1