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

React-GraphQL应用对接Camunda GraphQL API时如何解决CORS错误

解决React调用Camunda GraphQL API的CORS问题

方案一:直接配置Camunda允许跨域请求(推荐,若有权限修改Camunda服务器)

Camunda本身支持CORS配置,无需额外搭建Apollo Server,根据你的Camunda部署方式修改配置:

Spring Boot版Camunda

在application.properties中添加以下配置:

# 开启CORS
camunda.bpm.webapp.cors.enabled=true
# 允许你的React应用源
camunda.bpm.webapp.cors.allowed-origins=http://localhost:3000
# 允许的请求方法
camunda.bpm.webapp.cors.allowed-methods=GET,POST,OPTIONS
# 允许的请求头
camunda.bpm.webapp.cors.allowed-headers=Content-Type,Authorization

Camunda Run版

修改config/default.yml中的CORS配置段:

camunda.bpm:
  webapp:
    cors:
      enabled: true
      allowed-origins:
        - http://localhost:3000
      allowed-methods:
        - GET
        - POST
        - OPTIONS
      allowed-headers:
        - Content-Type
        - Authorization

配置完成后重启Camunda服务器即可。

方案二:搭建Express代理服务器(无Camunda服务器修改权限时使用)

通过Express代理转发React的请求,规避CORS限制,步骤如下:

  1. 初始化代理项目
mkdir camunda-graphql-proxy && cd camunda-graphql-proxy
npm init -y
npm install express http-proxy-middleware cors
  1. 创建代理服务器代码
    新建server.js文件,写入以下内容:
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors');

const app = express();

// 仅允许React应用的请求源
app.use(cors({ origin: 'http://localhost:3000' }));

// 转发GraphQL请求到Camunda API
app.use('/graphql', createProxyMiddleware({
  target: 'http://{my_ip}:8082', // 替换为你的Camunda API地址
  changeOrigin: true,
  onProxyReq: (proxyReq, req) => {
    // 传递认证头(如果你的API需要)
    if (req.headers.authorization) {
      proxyReq.setHeader('Authorization', req.headers.authorization);
    }
  }
}));

const PORT = 4000;
app.listen(PORT, () => {
  console.log(`代理服务器运行在 http://localhost:${PORT}`);
});
  1. 启动代理服务器
node server.js
  1. 修改React的Apollo Client配置
    将请求端点改为代理服务器地址:
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';

const httpLink = createHttpLink({
  uri: 'http://localhost:4000/graphql', // 代理服务器地址
});

const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
});

方案三:使用Create React App内置代理(最简方案,若用CRA创建项目)

如果你的React应用是用Create React App搭建的,直接在package.json中添加代理配置:

"proxy": "http://{my_ip}:8082"

然后修改Apollo Client的请求端点为相对路径:

const httpLink = createHttpLink({
  uri: '/graphql',
});

重启React应用后,所有请求会自动转发到Camunda API,无需额外代理服务器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:25:14