moh*_*med 22 javascript node.js express reactjs next.js
我想获取用户时区和位置以根据位置和时区呈现服务器端页面,但我无法从请求中获取用户 IP 地址或获取本地主机 IP 地址 (127.0.0.1)。所以我该怎么做 ?
Iva*_* V. 22
您可以使用request-ip包之类的东西。然后在你的 API 路径中:
import requestIp from 'request-ip'
export default async function myRoute(
req: NextApiRequest,
res: NextApiResponse
) {
const detectedIp = requestIp.getClientIp(req)
}
Run Code Online (Sandbox Code Playgroud)
Don*_*ito 22
能够使用 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,
},
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以使用 NextRequest 对象作为本机 Request 接口的直接替代品,从而使您能够更好地控制请求的操作方式。参考: https: //nextjs.org/docs/app/api-reference/functions/next-request
NextRequest 是完全类型化的,可以从 next/server 导入。
import type { NextRequest } from 'next/server'
Run Code Online (Sandbox Code Playgroud)
NextRequest 对象是本机 Request 接口的扩展,添加了以下方法和属性:
您还可以尝试使用页面的getInitialProps.
IndexPage.getInitialProps = async ({ req }) => {
const ip = req.headers["x-real-ip"] || req.connection.remoteAddress;
return { ip };
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64516 次 |
| 最近记录: |