【问题标题】:Read header from response with apollo-datasource-rest使用 apollo-datasource-rest 从响应中读取标头
【发布时间】:2021-05-21 22:58:41
【问题描述】:
import { RESTDataSource } from 'apollo-datasource-rest';
export class Foo extends RESTDataSource {
async getFoo(id) {
const responseFoo = await this.get(`/api/v1/foo/${id}`);
return FooReducer(responseFoo);
}
}
假设我使用 this.get 去做一个 GET 请求。如何读取响应中的标题? apollo-datasource-rest 包中完全没有这个吗?
【问题讨论】:
标签:
javascript
rest
apollo
【解决方案1】:
在 RESTDataSource 中的 didRecieveResponse 方法中,您可以访问响应对象。在 RESTDataSource 类中定义/覆盖如下:
export class Foo extends RESTDataSource {
async didReceiveResponse(response, request) {
// use this.authHeader value in the class anywhere
this.authHeader = response.headers.get('authorization');
}
async getFoo(id) {
const responseFoo = await this.get(`/api/v1/foo/${id}`);
console.log(this.authHeader)
return FooReducer(responseFoo);
}
}
willSendRequest 方法(您可以在其中访问 req 对象并设置标头等)在触发 http 请求之前运行,并且在收到来自 http 请求的响应后调用 didReceiveResponse 方法。