You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 08:45:32