我想获取用户的时区和位置信息,以根据其位置和时区呈现服务器端页面,但是我无法从请求中获取用户的IP地址或获取本地主机的IP地址(127.0.0.1)。那么我应该怎么办?
我想获取用户的时区和位置信息,以根据其位置和时区呈现服务器端页面,但是我无法从请求中获取用户的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)
}
使用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,
},
}
}
import type { NextRequest } from 'next/server'
NextRequest对象是原生请求接口的扩展,具有以下添加的方法和属性:
next/server
仅适用于 Next.js 12+ https://blog.logrocket.com/whats-new-next-js-12/ - James MurtyNextRequest
仅在 Edge Runtime
上可用。它无法在常规 API 路由或 Node.js 服务器端代码上工作。 - juliomalvesgetInitialProps
。IndexPage.getInitialProps = async ({ req }) => {
const ip = req.headers["x-real-ip"] || req.connection.remoteAddress;
return { ip };
};
import { NextApiRequest, NextApiResponse } from "next";
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
let ipAddress = req.headers["x-real-ip"] as string;
const forwardedFor = req.headers["x-forwarded-for"] as string;
if (!ipAddress && forwardedFor) {
ipAddress = forwardedFor?.split(",").at(0) ?? "Unknown";
}
res.status(200).json(ipAddress);
};
export default handler;
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 }
}