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

如何将RESTDataSource响应头传递至ApolloServer(Express)响应头

实现ApolloServer将第三方服务响应头传递给客户端

要把第三方服务的响应头传递给客户端,核心是让RESTDataSource能访问到ApolloServer的响应对象(res),具体实现步骤如下:

  • 在Apollo上下文里传递响应对象
    初始化ApolloServer时,把请求上下文里的res传入context,这样RESTDataSource就能通过this.context访问到它。

  • 修改自定义RESTDataSource类
    在didReceiveResponse方法中,从context拿到res,再遍历第三方服务的响应头,将需要的头设置到客户端响应中。

修改后的代码示例

自定义RESTDataSource类

export abstract class myClass extends RESTDataSource {
  // 声明context类型,确保能正确获取res对象
  context: { res: any };

  getSomething() {
    const endpoint = this.endpointPath;
    return this.get(endpoint);
  }

  async didReceiveResponse<T>(response: Response, request): Promise<T | null> {
    // 从context中拿到Apollo的响应对象
    const { res } = this.context;

    // 遍历第三方服务的响应头,设置到客户端响应里
    // 可以根据需求筛选要传递的头,避免传递无关或敏感头
    response.headers.forEach((value, key) => {
      // 示例:排除服务器、日期这类不需要传递的头
      if (!['server', 'date'].includes(key.toLowerCase())) {
        res.setHeader(key, value);
      }
    });

    if (response.ok) {
      return this.parseBody(response) as any as Promise<T>;
    } else {
      throw await this.errorFromResponse(response);
    }
  }
}

ApolloServer初始化代码

const apolloServer = new ApolloServer({
  context: async ({ res, req }) => {
    // 将res和req传入context,供RESTDataSource使用
    return { res, req };
  },
  // 这里补充你的typeDefs、resolvers等配置
});

额外注意事项

  • 如果涉及跨域,需要在CORS配置中添加exposedHeaders,指定允许客户端访问的响应头,否则客户端无法读取这些自定义传递的头。
  • 建议不要盲目传递所有第三方响应头,根据业务需求筛选必要的头,避免泄露服务内部信息或引发兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:25:43