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

Next.js客户端组件调用外部API返回403,服务端组件调用正常的问题求助

Next.js客户端组件调用外部API返回403,服务端组件调用正常的问题求助

就像标题说的,我在客户端组件里请求外部API时会返回403错误,但在服务端组件里调用却完全正常。

我需要在客户端发起请求的原因是,用户的选择会决定请求的参数,所以我用了useState()来管理选择状态:用户选一个行业板块(sector),然后根据板块ID去调用接口获取对应的细分行业(industry)列表。

下面是相关的客户端组件代码:

const { data: session } = useSession();
const [sector, setSector] = useState<Sector | null>(null);
const [industries, setIndustries] = useState<Industry[]>([]);
const [industry, setIndustry] = useState<Industry | null>(null);

const handleSectorSelection = (event: React.ChangeEvent<{}>, value: Sector | null) => {
  setSector(value);
};
const handleIndustrySelection = (event: React.ChangeEvent<{}>, value: Industry | null) => {
  setIndustry(value);
};

useEffect(() => {
  const getIndustries = async (sectorId: number) => {
    const response = await getIndustriesBySectorId(sectorId, session?.jwt);
    setIndustries(response.result as Industry[]);
  };
  if (sector && sector.id != null) {
    getIndustries(sector.id);
  } else {
    setIndustries([]);
  }
}, [sector, session?.jwt]);

return (
  // ... 其他渲染内容
  <SectorSelectDropdown
    options={sectors}
    onChange={handleSectorSelection}
    renderInput={(params) => <TextField {...params} label="Search" variant="outlined" />}
  />
  {industries && industries.length > 0 ? (
    <IndustrySelectDropdown
      options={industries}
      onChange={handleIndustrySelection}
      renderInput={(params) => <TextField {...params} label="Search" variant="outlined" />}
    />
  ) : null}
  // ... 其他渲染内容
);

注:sectors属性是从父组件传过来的

对应的API调用函数代码:

export async function getIndustriesBySectorId(sectorId: number, jwt?: string) {
  let result = null,
    error = null;
  if (!jwt) {
    throw new Error("Session JWT token not found.");
  }

  try {
    console.log(jwt);
    result = await fetch(`${process.env.NEXT_PUBLIC_POSITIONS_SERVICE_URL!}/industries/sector/${sectorId}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Cookie: `Authentication=${jwt}`,
      },
      credentials: "include",
    });
    if (!result.ok) {
      throw new Error(`Failed to fetch industry: ${result.statusText}`);
    }

    const data: Industry[] = await result.json();

    return { result: data, error: null };
  } catch (e) {
    error = e;
    return { result: {}, error: error };
  }
}

如果是在服务端组件里调用,我会直接在函数里获取session数据(而不是从外部传入),比如这样:

export async function getPositions() {
  const session = await getServerSession(authOptions);
  let result = null,
    error = null;

  if (!session?.jwt) {
    throw new Error("Session JWT token not found.");
  }
  // ... 后续API调用逻辑
}

现在想请教一下:有没有办法在现有架构下解决这个403的问题?或者有没有办法把我当前的客户端组件改成服务端组件?我刚接触Next.js,会不会我的整个架构设计就有问题?

备注:内容来源于stack exchange,提问作者codian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 16:23:23