在Astro中使用Apollo Client发起GraphQL请求时如何设置响应头
在Astro + Apollo Client中设置自定义响应头的正确方式
情况1:给Astro应用的HTTP响应设置自定义头(返回给浏览器)
你当前的代码思路存在问题——Apollo Link的执行上下文里无法直接访问Astro的响应对象(res),两者的运行上下文是分离的。正确的做法是在Astro的页面/组件/路由中,执行完GraphQL查询后,直接通过Astro内置的响应对象设置头:
--- // src/pages/your-page.astro import { client } from '../lib/apollo-client'; import { gql } from '@apollo/client/core'; // 执行GraphQL查询 const yourQuery = gql` query GetData { # 你的查询内容 } `; const { data } = await client.query({ query: yourQuery }); // 设置自定义响应头 Astro.response.headers.set('My-Custom-Header', 'my-value'); --- <!-- 页面渲染内容 --> <h1>{data?.someField}</h1>
如果需要在所有页面的GraphQL查询后自动设置头,可以封装一个通用查询函数:
// src/lib/apollo-utils.ts import { client } from './apollo-client'; import { DocumentNode } from '@apollo/client/core'; export async function queryWithHeader<T>(query: DocumentNode, variables?: Record<string, any>) { const result = await client.query<T>({ query, variables }); if (typeof Astro !== 'undefined') { Astro.response.headers.set('My-Custom-Header', 'my-value'); } return result; }
之后在页面中用这个函数替代直接调用client.query即可。
情况2:给GraphQL请求本身设置自定义请求头(发给GraphQL服务器)
如果你的需求是在发起GraphQL请求时,给请求带上自定义头(比如鉴权头),可以通过Apollo Link的setContext方法实现,这是Apollo Link的标准用法:
// src/lib/apollo-client.ts import { ApolloClient, InMemoryCache, ApolloLink, from } from '@apollo/client/core'; import { HttpLink } from '@apollo/client/link/http'; const httpLink = new HttpLink({ uri: '你的GraphQL服务器地址' }); // 创建自定义请求头Link const customHeaderLink = new ApolloLink((operation, forward) => { // 给请求设置自定义头 operation.setContext(({ headers }) => ({ headers: { ...headers, 'My-Custom-Header': 'my-value' } })); return forward(operation); }); export const client = new ApolloClient({ cache: new InMemoryCache(), ssrMode: true, link: from([customHeaderLink, httpLink]), });
内容的提问来源于stack exchange,提问作者meez
相关产品推荐
相关产品推荐

