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

在Next.js中调用外部公共API遇CORS错误,求解决方案及示例

Next.js 解决 CORS 请求失败的方案

方案1:利用 Next.js API 路由做代理(推荐)

浏览器的CORS限制仅针对前端直接发起的请求,通过后端代理可以完全绕开这个问题。

  1. 在项目的 pages/api 目录下创建 hello-proxy.js 文件
  2. 写入代理逻辑:
export default async function handler(req, res) {
  try {
    const targetRes = await fetch('http://127.0.0.1:5001/helloWorld', {
      method: 'GET',
    });
    const responseData = await targetRes.text(); // 若API返回JSON则用.json()
    res.status(targetRes.status).send(responseData);
  } catch (err) {
    res.status(500).json({ error: '代理请求失败' });
  }
}
  1. 前端修改请求目标为代理路由:
let fetched = await fetch('/api/hello-proxy')
  .then(result => {
    console.log('请求完成', result.status);
    return result;
  });

方案2:配置 Next.js 重写规则

无需编写API路由,直接在 next.config.js 中配置请求转发:

/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/api/hello',
        destination: 'http://127.0.0.1:5001/helloWorld',
      },
    ];
  },
};

module.exports = nextConfig;

前端直接请求 /api/hello 即可,请求逻辑和方案1一致。

方案3:临时启用 no-cors 模式(不推荐)

如果不需要读取响应内容,仅需完成请求动作,可以按照错误提示设置 mode: 'no-cors',但此模式下无法获取响应状态、数据等信息:

let fetched = await fetch('http://127.0.0.1:5001/helloWorld', {
  method: 'GET',
  mode: 'no-cors',
}).then(() => {
  console.log('请求完成(无法读取响应内容)');
});

补充说明

你之前在Angular中能成功发起请求,大概率是因为Angular开发服务器默认配置了代理规则,而Next.js没有内置这类配置,所以需要手动通过上述方式绕开CORS限制。

内容的提问来源于stack exchange,提问作者dankoiDev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:25:19