在Next.js的getServerSideProps中调用API,请求方IP是客户端还是服务器IP?
getServerSideProps中API请求的IP来源
在Next.js的getServerSideProps函数内发起的API请求,请求方IP是运行Next.js应用的服务器IP,而非客户端IP。
原因
getServerSideProps是完全在服务器端执行的函数,所有内部的请求操作都是从Next.js部署所在的服务器发出的,和客户端环境没有直接关联。
如何传递客户端IP给目标API
如果需要让目标API获取到客户端的真实IP,可以从getServerSideProps的上下文参数中提取客户端IP,再通过请求头或请求参数传递给API:
export const getServerSideProps = async (context) => { // 获取客户端IP(反向代理场景下优先取x-forwarded-for) const clientIp = context.req.headers['x-forwarded-for'] || context.req.connection.remoteAddress; // 携带客户端IP发起请求 const res = await axios.get('some url', { headers: { 'X-Client-IP': clientIp } }); return { props: {} }; };
另外,你提供的代码里存在笔误:cont应改为const。
内容的提问来源于stack exchange,提问作者soroshzzz26
相关产品推荐
相关产品推荐

