在NextJS上获取客户端IP并使用SSR

问题描述 投票:0回答:3

我正在制作一个天气应用程序,我使用 IPIFY 获取客户端 IP,但这会丢失 SSR,或者我使用 SSR 并获取服务器 IP。有人告诉 我知道我可以使用标头

x-forwarded-for
,然后使用这个值,通过 SSR 进行天气 API 调用。

问题是我只使用nextjs,这里没有后端,其次,我不知道如何调用或使用前面的

x-forwarded-for
来获取客户端IP。

  1. 这可以吗?

  2. 我该如何实现?

我正在使用 vercel 来部署应用程序。

ip next.js server-side-rendering clientip
3个回答
7
投票

更新的答案为

request.connection
自 Node.js v13.0.0 起已被弃用。所以我们现在应该使用 request.socket
 来代替。

export const getServerSideProps = async ({ req }) => { const forwarded = req.headers['x-forwarded-for']; const ip = typeof forwarded === 'string' ? forwarded.split(/, /)[0] : req.socket.remoteAddress; console.log(ip); return { props: { ip }, }; };
    

2
投票
给你:

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

0
投票
我认为你可以通过

getServerSideProps 获得它们。

export async function getServerSideProps({ req }) { console.log(req.headers) //see if you have those headers return { props: { headers }, } } function Page({ headers }) { // Render data... }
    
© www.soinside.com 2019 - 2024. All rights reserved.