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

如何在Fastify服务器中配置CORS适配React的Apollo Client

解决Fastify + React Apollo Client的CORS问题

核心问题

你的Fastify服务器未正确返回Access-Control-Allow-Origin响应头,导致前端跨域请求被浏览器拦截。以下是针对性的排查和解决步骤:


1. 确保使用官方最新CORS插件

Fastify官方已将CORS插件迁移到@fastify/cors(旧版fastify-cors已废弃),先确认安装正确:

npm install @fastify/cors
# 或
yarn add @fastify/cors

2. 正确注册CORS插件(关键:顺序优先)

CORS插件必须在所有路由、GraphQL插件之前注册,否则请求到达业务路由时,CORS头还未被设置。以下是完整配置示例:

const Fastify = require('fastify')
const cors = require('@fastify/cors')
const { graphqlFastify } = require('@fastify/graphql')
const { buildSchema } = require('graphql')

const fastify = Fastify({ logger: true })

// 第一步:注册CORS插件
fastify.register(cors, {
  origin: 'http://localhost:3000', // 明确指定前端地址,禁止用*(若需携带凭证)
  credentials: true, // 若前端请求带cookie/Authorization头,必须开启
  allowedHeaders: ['Content-Type', 'Authorization'], // 允许前端自定义头
  methods: ['GET', 'POST', 'OPTIONS'] // 覆盖默认方法,确保包含预检请求OPTIONS
})

// 第二步:注册GraphQL路由
const schema = buildSchema(`
  type Query {
    hello: String
  }
`)

const root = {
  hello: () => 'Hello World!'
}

fastify.register(graphqlFastify, {
  prefix: '/graphql',
  schema: schema,
  rootValue: root,
  graphiql: true
})

// 启动服务器
fastify.listen({ port: 3001 }, (err) => {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

3. 排查常见失效原因

  • 插件顺序错误:如果先注册GraphQL再注册CORS,CORS中间件不会作用于GraphQL路由,这是最常见的坑。
  • 手动设置CORS头冲突:不要同时在路由里手动添加Access-Control-Allow-Origin头,会和插件的设置冲突。
  • 预检请求被拦截:Fastify CORS插件会自动处理OPTIONS预检请求,若你自定义了OPTIONS路由,会覆盖插件逻辑,导致预检失败。
  • Apollo Client配置问题:确保客户端请求未携带未被允许的头,或在Apollo Client中开启credentials: 'include'(若服务器开启了credentials: true):
    import { ApolloClient, InMemoryCache } from '@apollo/client';
    
    const client = new ApolloClient({
      uri: 'http://localhost:3001/graphql',
      cache: new InMemoryCache(),
      credentials: 'include' // 对应服务器的credentials配置
    });
    

4. 验证CORS配置是否生效

用curl命令测试响应头:

curl -H "Origin: http://localhost:3000" -I http://localhost:3001/graphql

若响应头包含Access-Control-Allow-Origin: http://localhost:3000,则配置生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:09:55