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

ApolloClient未设置Authorization Header问题求助

问题:Expo中Apollo Client无法传递Authorization Header

问题详情

我开发了一个基于GraphQL API的Expo应用,需要在每个请求中携带Authorization Token,但当前客户端配置并未成功设置或发送该请求头。

在graphql.config.yml中配置Authorization Header可以正常生效:

schema: schema.graphql
extensions:
  endpoints:
    Dev Backend:
      url: http://localhost:8000/graphql
      introspect: true
      headers:
        authorization: "My token"

但实际客户端发送请求后,后端记录的请求头中没有Authorization字段:

Headers({
    'content-length': '113',
    'content-type': 'application/json; charset=UTF-8',
    'host': 'localhost:8000',
    'connection': 'Keep-Alive',
    'user-agent': 'Apache-HttpClient/4.5.14 (Java/17.0.7)',
    'accept-encoding': 'gzip,deflate'
})

以下是客户端的Apollo配置代码:

import {ApolloClient, InMemoryCache, ApolloLink, concat} from '@apollo/client';
import {setContext} from '@apollo/client/link/context';
import {getUserSession} from "./session-handler";
import {createUploadLink} from "apollo-upload-client";
    
// Create an HTTP link to your GraphQL server
const httpLink = createUploadLink({
  uri: 'http://localhost:8000/',
  credentials: 'include',
});
    
const authMiddleware = new ApolloLink((operation, forward) => {
  // add the authorization to the headers
  operation.setContext(({ headers = {} }) => ({
    headers: {
      ...headers,
      authorization: "THIS IS A TEST TOKEN",
    }
  }));
    
  return forward(operation);
})
    
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: concat(authMiddleware, httpLink),
});
    
export {
  client
};

修复方案

1. 修正HTTP Link的URI路径

当前createUploadLink的uri是http://localhost:8000/,但实际GraphQL接口路径是http://localhost:8000/graphql,路径不匹配会导致请求发送到错误地址,后端无法正确处理。修改代码:

const httpLink = createUploadLink({
  uri: 'http://localhost:8000/graphql', // 补充完整的GraphQL接口路径
  credentials: 'include',
});

2. 使用官方推荐的setContext处理请求头

虽然自定义ApolloLink逻辑本身没问题,但官方推荐使用setContext来管理请求上下文,写法更简洁且不易出错:

// 替换原有的authMiddleware
const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: "THIS IS A TEST TOKEN",
    }
  };
});

// 组合链路
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: concat(authLink, httpLink),
});

3. 验证请求头是否实际发送

可以通过Expo的网络调试工具查看客户端发送的请求详情,确认Authorization Header是否被正确添加。有时候后端日志可能存在捕获遗漏,先在客户端层面验证请求的正确性。

4. 确认链路顺序

确保认证链路(authMiddleware/authLink)在HTTP链路之前,concat(authLink, httpLink)的顺序是正确的,这样认证逻辑才能在请求发送前修改头信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:53:10