Apollo Client配置credentials时出现CORS问题求助
NextJS中Apollo Client配置credentials时CORS问题的解决方法
下面是针对你遇到的「Apollo Client加credentials: 'include'触发CORS错误,但原生fetch同配置正常」问题的几个排查和解决方向:
对齐Apollo Client与原生fetch的请求头
Apollo Client默认会添加一些自定义请求头(比如apollographql-client-name、apollographql-client-version),如果后端CORS配置未允许这些头,就会触发错误。手动将HttpLink的请求头设置为和原生fetch一致,覆盖默认值:const httpLink = new HttpLink({ uri: 'http://localhost:4000/graphql', credentials: 'include', headers: { accept: '*/*', 'content-type': 'application/json' } }); const client = new ApolloClient({ cache, link: httpLink });验证后端CORS配置的关键参数
即使你说后端已配置CORS,仍需确认以下几点:Access-Control-Allow-Origin不能设为*,必须是前端的具体域名(比如http://localhost:3000),带credentials时通配符不被允许;- 必须显式设置
Access-Control-Allow-Credentials: true; - 如果Apollo发送了自定义头,需在
Access-Control-Allow-Headers中包含这些头,或者临时设为*(生产环境不推荐)。
用NextJS API路由做代理绕过CORS
如果上述方法无效,可以通过NextJS的API路由创建代理,将前端请求转发到GraphQL后端,这样浏览器端是同域请求,不会触发CORS检查:- 在
pages/api/graphql.js中创建代理:
import { createProxyMiddleware } from 'http-proxy-middleware'; export default function handler(req, res) { createProxyMiddleware({ target: 'http://localhost:4000', changeOrigin: true, credentials: true, pathRewrite: { '^/api/graphql': '/graphql' }, })(req, res); }- 修改Apollo Client的uri为代理地址:
const client = new ApolloClient({ uri: '/api/graphql', cache, credentials: 'include' });- 在
升级Apollo Client到最新稳定版
部分旧版本的Apollo Client在credentials参数处理上存在bug,尝试升级@apollo/client到v3.x的最新版本,再测试是否解决问题。
内容的提问来源于stack exchange,提问作者dawudarif
相关产品推荐
相关产品推荐

