【问题标题】:How to include headers in RESTDataSource request?如何在 RESTDataSource 请求中包含标头?
【发布时间】:2019-09-17 15:33:36
【问题描述】:

我正在尝试使用 apollo RESTDataSource 来包装我的 rest api。我需要将一些标头传递给 api 调用。

我正在关注文档中的示例:https://www.apollographql.com/docs/apollo-server/features/data-sources#intercepting-fetches

这是我的代码:

  willSendRequest(request: RequestOptions) {
    console.log(`request 1: ${JSON.stringify(request)}`);
    request.headers.set('Authorization', this.context.authorization);
    console.log(`request 2: ${JSON.stringify(request)}`);
  }

我希望标题包含“授权”。但它总是空的。

以上代码的日志:

request 1: {"method":"POST","path":"partnerinvoices","body":{"command": "input","params":{},"headers":{}}
request 2: {"method":"POST","path":"partnerinvoices","body":{"command":"input","params":{},"headers":{}}

我可以毫无问题地覆盖 willSendRequest 方法中的 body 和 params。

【问题讨论】:

    标签: javascript apollo-server


    【解决方案1】:

    您需要使用request.headers.get('Authorization') 来获取您想要的数据。使用 JSON.stringify 不会为您提供标头值,因为它不是对象文字。

    willSendRequest(request: RequestOptions) {
        console.log(`request 1: ${request.headers.get('Authorization')}`);
        request.headers.set('Authorization', this.context.authorization);
        console.log(`request 2: ${request.headers.get('Authorization')}`);
      }
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Typescript,请务必匹配 willSendRequest 方法的原始签名:

      protected willSendRequest?(request: RequestOptions): ValueOrPromise<void>;
      

      (链接到docs

      所以,请确保方法如下所示:

          protected willSendRequest?(request: RequestOptions): ValueOrPromise<void> {
              request.headers.set("Authorization", this.context.authorization);
          }
      

      【讨论】:

        【解决方案3】:

        有几种方法可以实现这一点,

        在扩展 RESTDataSource 的 Datasources 类中,在发出请求之前设置标头

        willSendRequest(request) {
         request.headers.set('Authorization', 'Bearer .....')
        }
        

        或作为数据源方法中的第三个参数(post、get、put、...)

        this.post('endpoint', {}, { headers: { 'Authorization': 'Bearer ...' } })
        

        【讨论】:

        • 您提供的第一个实现与@clothoo 没有工作的完全相同。我遇到了同样的问题,似乎标题不会被设置。您是否找到比在每个请求中添加标头更好的解决方案?
        猜你喜欢
        • 1970-01-01
        • 2013-10-27
        • 1970-01-01
        • 2020-01-19
        • 2016-11-07
        • 1970-01-01
        • 2017-02-24
        • 2018-11-11
        • 1970-01-01
        相关资源
        最近更新 更多