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 请求。如何阅读响应中的 header ?这在 apollo-datasource-rest
包中是否完全缺失?
最佳答案
在RESTDataSource中的didRecieveResponse方法中,可以访问response对象。在 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 方法(您可以在其中访问请求对象和设置 header 等)在触发 http 请求之前运行,并在收到来自 http 请求的响应后调用 didReceiveResponse 方法。
关于javascript - 使用 apollo-datasource-rest 从响应中读取 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60764956/