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

React发送跨域请求报CORS policy错误,服务端使用Koa框架如何解决?

跨域问题解决方案

报错核心原因有两点:

  1. 前端axios直接请求http://localhost:8000/hello端口,未走同源服务代理,触发浏览器CORS校验
  2. Koa侧createProxyMiddleware用法错误,中间件未被正确执行,代理逻辑不生效

方案一:前端配置本地代理(开发环境最优解)

  • 先修改前端请求地址为相对路径,默认走React服务所在的http://localhost:3000域名:
function SendRequest() {
    axios({
        url: "/hello",
        method: "GET",
    }).then((res)=>
    {
        console.log(res);
    });
}
  • 如果你用的是Create React App脚手架,在项目根目录新建setupProxy.js,先安装依赖npm install http-proxy-middleware --save,再写入配置:
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/hello',
    createProxyMiddleware({
      target: 'http://localhost:8000',
      changeOrigin: true,
    })
  );
};

配置完成后重启React开发服务即可,所有/hello开头的请求会自动代理到8000端口,无跨域问题。

方案二:Koa服务端开启CORS

如果不需要前端代理,直接在Koa侧配置跨域头即可,不需要用代理中间件:

  • 安装koa2-cors依赖:npm install koa2-cors --save
  • 修改Koa服务代码,在所有路由前挂载CORS中间件:
const cors = require('koa2-cors');

app.use(cors({
  origin: 'http://localhost:3000', // 允许前端3000端口跨域访问
  credentials: true // 如需跨域传递cookie可开启,否则可删除
}));

// 原有业务路由逻辑
app.use(async ctx => {
  if(ctx.path === '/hello') {
    ctx.body = '接口返回内容';
  }
});

不想用第三方依赖也可以手动写中间件添加响应头:

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', 'http://localhost:3000');
  ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  // 处理OPTIONS预检请求
  if (ctx.method === 'OPTIONS') {
    ctx.status = 204;
  } else {
    await next();
  }
});

方案三:修正当前Koa代理写法(不推荐,逻辑冗余)

你现有的Koa代理代码仅定义了代理中间件未执行,所以不生效,修正后写法如下:

const { createProxyMiddleware } = require('http-proxy-middleware');
const Koa = require('koa');
const app = new Koa();

// 直接挂载代理中间件,无需包裹自定义中间件
app.use(createProxyMiddleware('/hello', {
  target: "http://localhost:8000",
  changeOrigin: true
}));

该方案需要前端请求Koa服务的端口,如果你当前Koa本身就运行在8000端口,该方案完全无意义,直接用方案二即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:06:02