apollo-link-http 全选项解析:HttpLink 动态鉴权、GET/POST 切换与自定义 fetch 完整指南
apollo-link-http 全选项解析:HttpLink 动态鉴权、GET/POST 切换与自定义 fetch 完整指南
apollo-link-http 是 Apollo Client 生态中最常用的 Link,它通过 createHttpLink 创建的 HttpLink 负责把 GraphQL 请求发送到服务端。本文将逐个解析 HttpLink 的全部配置选项,并给出动态鉴权、GET/POST 方法切换与自定义 fetch 三大场景的实用方案,帮助新手快速掌握这款 GraphQL 请求库的核心用法。
一、先认识 HttpLink:请求链中的"最后一站"
在 Apollo Link 架构中,请求会像流水线一样穿过一个个 Link(如鉴权 Link、重试 Link、错误 Link),而 HttpLink 是终结 Link(terminating link)——它位于链路末端,真正把请求发出去。
最简初始化只需要两行代码:
import { createHttpLink } from "apollo-link-http";
const link = createHttpLink({ uri: "/graphql" });
它的完整实现位于 httpLink.ts,官方说明见 docs/source/links/http.md 与 apollo-link-http/README.md。
二、7 个核心选项一览表:createHttpLink 快速上手
HttpLink 的选项类型定义在 HttpOptions,一目了然:
| 选项 | 默认值 | 作用 |
|---|---|---|
uri |
/graphql |
接口地址,支持字符串或函数(按请求动态计算) |
headers |
accept: */*、content-type: application/json |
请求头,鉴权就靠它 |
credentials |
不设置 | 凭证策略:omit、include、same-origin |
fetchOptions |
method: POST |
透传给 fetch 的任意参数,可覆盖 method 等 |
includeExtensions |
false |
是否把 extensions 字段发给服务端 |
fetch |
全局 fetch |
可替换为任意兼容 fetch 接口的函数 |
useGETForQueries |
不开启 | 对 query 类请求改用 GET,mutation 仍走 POST |
默认配置定义在 fallbackHttpConfig,这也是理解后文"优先级"的关键。
三、动态鉴权教程:用 context 注入 Authorization 请求头
HttpLink 读取 context.headers 并将其合并进请求头,这是实现动态鉴权最推荐的方式——在前置的鉴权 Link 中设置 token,HttpLink 自动生效:
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
authorization: localStorage.getItem("token") || null,
},
});
return forward(operation);
});
const link = authLink.concat(httpLink);
三个进阶细节:
- 按请求覆盖请求头:Apollo Client 支持为单次
client.query传入context,可为某一次请求单独附加特殊请求头; - 客户端标识:在 context 中设置
clientAwareness: { name, version },HttpLink 会自动加上apollographql-client-name/version请求头(见 httpLink.ts#L67-L84),服务端可据此统计客户端版本; - 原始响应可读:请求完成后,原始
Response对象会写入context.response,后续 Link 可直接读取状态码等信息。
四、GET/POST 切换指南:useGETForQueries 的正确用法与避坑
默认情况下 HttpLink 一律使用 POST 发送请求体。若想对查询类请求使用 GET(常见于 CDN 缓存、浏览器历史分享等场景),正确姿势是设置:
createHttpLink({ uri: "/graphql", useGETForQueries: true });
开启后,HttpLink 会检查该操作是否包含 mutation(httpLink.ts#L108-L117):
- 纯 query → 改为 GET,并把
query、operationName、variables、extensions序列化后拼进 URL 查询参数(逻辑见 rewriteURIForGET),符合 GraphQL over HTTP 的 GET 编码规范; - 含 mutation → 仍走 POST,保证非幂等操作的安全性。
⚠️ 常见坑:不要通过 fetchOptions: { method: "GET" } 来"全局强切 GET",那样 mutation 也会被强制 GET。官方文档明确建议:只让查询走 GET、mutation 保持 POST 时,请优先使用 useGETForQueries(详见 README 的 Context 章节)。
五、自定义 fetch 实战:签名鉴权与动态 URI
fetch 选项让你可以整体替换发请求的函数,拿到 (uri, options) 后想怎么改都行。两个官方推荐场景:
1. 签名类鉴权(如 Hawk、AWS SigV4)
const customFetch = (uri, options) => {
const { header } = Hawk.client.header(uri, "POST", { credentials });
options.headers.Authorization = header;
return fetch(uri, options);
};
const link = createHttpLink({ fetch: customFetch });
2. 按操作动态改写地址
const customFetch = (uri, options) => {
const { operationName } = JSON.parse(options.body);
return fetch(`${uri}/graph/graphql?opname=${operationName}`, options);
};
类似"按条件路由"的思路,也可以不用自定义 fetch,直接把 uri 写成函数(定义见 UriFunction),依据 operation 返回不同端点,比如按操作名分流到不同网关:
createHttpLink({
uri: operation => (operation.operationName === "AdminQuery"
? "/admin/graphql"
: "/graphql"),
});
另外注意:若运行环境没有全局 fetch(如 Node 服务端),checkFetcher 会直接抛出带修复提示的错误(checkFetcher),此时务必通过 fetch 选项传入 node-fetch 等 polyfill。
六、三层配置优先级:默认值、Link 选项、context 谁说了算?
每次请求的最终配置由 selectHttpOptionsAndBody 按以下顺序逐层合并,后者覆盖前者:
- 默认值(fallbackHttpConfig):POST、JSON 请求头、
includeQuery: true、includeExtensions: false; - Link 创建时的选项:
createHttpLink({...})传入的配置; - context:单次请求通过
operation.setContext(...)写入的配置。
也就是说,context 的优先级最高。URI 的选取同样遵循这一逻辑:context.uri > uri 函数 > 字符串(selectURI)。
七、按请求覆盖配置:context 能改的 4 样东西与持久化查询
在 context 中,HttpLink 识别以下字段,可随时动态生效:
| context 字段 | 说明 |
|---|---|
headers |
覆盖本次请求的请求头 |
credentials |
覆盖凭证策略 |
uri |
覆盖本次请求的接口地址 |
fetchOptions |
覆盖本次请求的 fetch 参数(如 method) |
http |
精细控制:includeQuery、includeExtensions |
持久化查询(Persisted Queries) 正是利用 http 字段实现的——不发送完整 query 字符串,只发一个标识,能显著减小请求体积:
operation.setContext({
http: {
includeExtensions: true, // 发送 extensions 字段
includeQuery: false, // 不发送 query 字符串
},
});
八、HttpLink 常见错误类型速查表
排查网络问题时,先分清错误属于哪一类(定义见 apollo-link-http-common/src/index.ts):
| 错误类型 | 触发场景 |
|---|---|
ClientParseError |
请求体无法序列化(如循环引用) |
ServerParseError |
服务端响应无法 JSON 解析 |
ServerError |
HTTP 状态码 ≥ 300,或响应缺少 data/errors |
| GraphQL Error | 2xx 状态码下 errors 数组中的业务错误 |
小技巧:即使是 401 这类"网络错误",只要响应里带了 data,HttpLink 也会先把结果 next 给下游再报错,让 UI 能同时展示可用数据与错误提示(见 httpLink.ts#L146-L185)。
九、组合示例:一套可直接借鉴的配置
把动态鉴权 + GET/POST 切换 + 错误处理串起来,一个生产级雏形大致如下:
import { createHttpLink } from "apollo-link-http";
import { onError } from "apollo-link-error";
const httpLink = createHttpLink({
uri: "https://api.example.com/graphql",
useGETForQueries: true,
headers: { "x-app-name": "my-app" },
});
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
authorization: localStorage.getItem("token") || null,
},
});
return forward(operation);
});
const link = onError(({ networkError }) => {
if (networkError && networkError.statusCode === 401) logout();
}).concat(authLink, httpLink);
写在最后
uri决定"发到哪",headers+ context 解决"动态鉴权",useGETForQueries决定"query 走 GET 还是 POST",fetch选项则是最后的万能逃生口;- 记住三层优先级:context > Link 选项 > 默认值,绝大多数定制需求用 context 就能优雅解决;
- 更多场景(批量、去重、重试等)可继续阅读本仓库 docs/source/links/ 下的各专题文档。

