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

使用Apollo Client调用GraphQL接口时出现CORS错误(发起者:createHttpLink.ts:185)

解决Apollo Client访问GraphQL服务器时的CORS错误

问题场景

我用Apollo Client配合GraphQL请求一台无直接访问权限的服务器,已经拿到合法访问令牌,但发起请求时触发了fetch类型的CORS错误,报错来源指向createHttpLink.ts:185。试过用公共CORS代理但没解决问题,相关代码如下:

Apollo Client配置代码

import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  createHttpLink,
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context";

const httpLink = createHttpLink({
  uri: api,
});

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization:
        "Bearer token",
    },
  };
});

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

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);

GraphQL查询定义

import { gql } from "@apollo/client";

export const GET_ALL_PROFILES = gql`
  query GetAllProfiles {
    profiles {
      id
      first_name
      last_name
      email
      is_verified
      image_url
      description
    }
  }
`;

组件中调用查询

import { Hidden, Button, Grid, TextField, Typography } from "@mui/material";
import { PersonAdd } from "@mui/icons-material";
import { ViewWeek } from "@mui/icons-material";
import { List } from "@mui/icons-material";
import { useQuery } from "@apollo/client";
import { GET_ALL_PROFILES } from "../../graphQL/schemas";

import "../../styles/grid/gridPage.scss";

const GridPage = () => {
  const { loading, error, data } = useQuery(GET_ALL_PROFILES);

  if (loading) {
    return console.log("loading still");
  } else if (error) {
    return console.log("error still");
  } else {
    return console.log("Data", data);
  }
}

可行解决方案

1. 本地开发代理(最推荐)

如果是React项目,直接在package.json中添加代理配置,让开发服务器自动转发请求:

"proxy": "https://你的目标服务器域名"

然后修改Apollo的请求地址为相对路径:

const httpLink = createHttpLink({
  uri: "/graphql", // 替换为目标服务器的GraphQL端点路径
});

这种方式完全绕过浏览器的CORS检查,适合本地开发阶段。

2. 自定义代理服务器

如果本地代理不适用,自己搭一个轻量代理服务器转发请求(避免依赖公共代理的限制和风险):
用Node.js+Express快速实现:

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();

// 转发GraphQL请求到目标服务器
app.use('/graphql', createProxyMiddleware({
  target: 'https://目标服务器域名',
  changeOrigin: true,
  headers: {
    // 可在这里统一添加授权头,或者保持前端传递
  }
}));

app.listen(3001);

然后修改Apollo的请求地址为本地代理地址:

const httpLink = createHttpLink({
  uri: "http://localhost:3001/graphql",
});

3. 服务器端配置CORS(有权限时)

如果能修改目标服务器的配置,直接在GraphQL服务中添加CORS允许规则:
以Express+Apollo Server为例:

const corsOptions = {
  origin: '你的前端域名', // 比如http://localhost:3000
  credentials: true,
  allowedHeaders: ['Content-Type', 'Authorization'],
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  cors: corsOptions,
});

这种方式从根源解决CORS问题,适合生产环境。

注意事项

  • 生产环境禁止使用公共CORS代理,存在数据泄露风险
  • 确认Authorization头格式正确:Bearer 后必须跟空格和令牌
  • 查看浏览器控制台的具体错误信息,比如是Access-Control-Allow-Origin不匹配,还是自定义头未被允许,针对性调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:37:00