【问题标题】:How do I set the response header from a server using an apollo server?如何使用 apollo 服务器从服务器设置响应标头?
【发布时间】:2019-04-27 17:13:04
【问题描述】:

我有一个应用程序可以在用户令牌过期时更新它。我需要使用此令牌更新客户端以防止错误。我实际上无法将新令牌发送到前端,因为似乎无法在响应中设置任何内容。如果有帮助,我会在后端使用 Graphql 和护照。

我尝试过 res.send、res.setheader 等...

有谁知道如何从 apollo 服务器向 apollo 客户端发送一个新的标头条目?

【问题讨论】:

  • 你能把令牌放在标准响应正文而不是标题中吗?
  • 您尝试过 ApolloLink 吗?这似乎非常适合使用 ApolloLink

标签: node.js reactjs graphql apollo apollo-client


【解决方案1】:

我认为您的 ApolloServer 构造函数的 formatResponse 参数应该对您有所帮助。这允许您在将来自服务器的响应发送到客户端应用程序之前对其进行处理。该函数将GraphQLResponseGraphQLRequestContext 作为输入并返回GraphQLResponseGraphQLResponse的接口是as follows

export interface GraphQLResponse {
  data?: Record<string, any> | null;
  errors?: ReadonlyArray<GraphQLFormattedError>;
  extensions?: Record<string, any>;
  http?: Pick<Response, 'headers'> & Partial<Pick<Mutable<Response>, 'status'>>;
}

这意味着您可以使用附加参数配置您的服务器,以便在响应发送到客户端之前对其进行解析:

const myServer = new ApolloServer(
   ...,
   formatResponse: (response, requestContext) => {
       // then create a new response here with your additional headers and return it, for instance
       const newResponse = { ...response, http: { response.http, { headers: ...response.http.headers, newHeader: newValue };
       return newResponse;
   }

请注意,以上只是一个框架,您需要更彻底地检查响应对象,因为它的属性在很大程度上是可选的,但这应该会给您提供要点。

更多详情请见documentation here

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 2016-06-04
    • 2021-10-27
    • 2018-02-11
    • 2017-07-11
    • 1970-01-01
    • 2021-08-29
    • 2017-02-07
    • 2015-03-14
    相关资源
    最近更新 更多