繁体   English   中英

如何在 next.js 应用程序中从服务器端获取客户端的 ip 地址?

[英]how to get the ip address of the client from server side in next.js app?

我想根据位置和时区获取用户时区和位置以呈现服务器端页面,但我无法从请求中获取用户 IP 地址或获取本地主机 IP 地址(127.0.0.1)。 所以我该怎么做?

您可以使用request-ip包之类的东西。 然后在您的 API 路线中:

import requestIp from 'request-ip'

export default async function myRoute(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const detectedIp = requestIp.getClientIp(req)
}

您也可以尝试使用页面的getInitialProps

IndexPage.getInitialProps = async ({ req }) => {
  const ip = req.headers["x-real-ip"] || req.connection.remoteAddress;
  return { ip };
};

代码沙盒示例

能够使用 next.js 应用程序检测用户 IP 地址:

export async function getServerSideProps({ req }) {
  const forwarded = req.headers["x-forwarded-for"]
  const ip = forwarded ? forwarded.split(/, /)[0] : req.connection.remoteAddress
  return {
    props: {
      ip,
    },
  }
}

您可以使用 NextRequest 对象作为本机 Request 接口的直接替代品,让您可以更好地控制如何操作请求。 参考: https : //nextjs.org/docs/api-reference/next/server#nextrequest

NextRequest 是完全类型化的,可以从 next/server 导入。

import type { NextRequest } from 'next/server'

NextRequest 对象是原生 Request 接口的扩展,添加了以下方法和属性:

  1. cookies - 有来自请求的 cookies
  2. nextUrl - 包括一个扩展的、解析过的 URL 对象,让您可以访问 Next.js 特定的属性,例如路径名、basePath、trailingSlash 和 i18n
  3. geo - 具有来自请求的地理位置
  4. geo.country - 国家代码
  5. geo.region - 地区代码
  6. geo.city - 城市
  7. geo.latitude - 纬度
  8. geo.longitude - 经度
  9. ip - 具有请求的 IP 地址
  10. ua - 有用户代理

通常当用户在 NextJS 中发送请求时,该请求包含一个具有属性的套接字实例,这可以是远程 IP 地址,以及远程端口等有用信息。

因此,对于正在寻找确切如何获取连接远程端的 IP 地址的任何人,您可以执行以下操作

Login.getInitialProps = async ({ req, res }: any) => {
  const ip = req.connection.remoteAddress
  // and use some other api to get location like country from the ip address
  return { ip }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM