简体   繁体   English

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

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

I want to get the user time zone and location to render a server-side page depending on the location and time zone but I can't get the user IP address from the request or get the localhost IP address (127.0.0.1).我想根据位置和时区获取用户时区和位置以呈现服务器端页面,但我无法从请求中获取用户 IP 地址或获取本地主机 IP 地址(127.0.0.1)。 so what should I do?所以我该怎么做?

You can use something like request-ip package.您可以使用request-ip包之类的东西。 Then in your API route:然后在您的 API 路线中:

import requestIp from 'request-ip'

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

You can also try using page's getInitialProps .您也可以尝试使用页面的getInitialProps

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

codesandbox example 代码沙盒示例

Was able to detect user IP address with next.js app:能够使用 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,
    },
  }
}

You can use the NextRequest object as a direct replacement for the native Request interface, giving you more control over how you manipulate the request.您可以使用 NextRequest 对象作为本机 Request 接口的直接替代品,让您可以更好地控制如何操作请求。 Ref: https://nextjs.org/docs/api-reference/next/server#nextrequest参考: https : //nextjs.org/docs/api-reference/next/server#nextrequest

NextRequest is fully typed and can be imported from next/server. NextRequest 是完全类型化的,可以从 next/server 导入。

import type { NextRequest } from 'next/server'

The NextRequest object is an extension of the native Request interface, with the following added methods and properties: NextRequest 对象是原生 Request 接口的扩展,添加了以下方法和属性:

  1. cookies - Has the cookies from the Request cookies - 有来自请求的 cookies
  2. nextUrl - Includes an extended, parsed, URL object that gives you access to Next.js specific properties such as pathname, basePath, trailingSlash and i18n nextUrl - 包括一个扩展的、解析过的 URL 对象,让您可以访问 Next.js 特定的属性,例如路径名、basePath、trailingSlash 和 i18n
  3. geo - Has the geo location from the Request geo - 具有来自请求的地理位置
  4. geo.country - The country code geo.country - 国家代码
  5. geo.region - The region code geo.region - 地区代码
  6. geo.city - The city geo.city - 城市
  7. geo.latitude - The latitude geo.latitude - 纬度
  8. geo.longitude - The longitude geo.longitude - 经度
  9. ip - Has the IP address of the Request ip - 具有请求的 IP 地址
  10. ua - Has the user agent ua - 有用户代理

Usually when the user sends a request in NextJS the request contains a socket instance that has properties, this can be the remote IP address, and remote port and other useful information.通常当用户在 NextJS 中发送请求时,该请求包含一个具有属性的套接字实例,这可以是远程 IP 地址,以及远程端口等有用信息。

So for anyone looking for exactly how to get this IP address of the connection remote end, you can do something like this因此,对于正在寻找确切如何获取连接远程端的 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