我正在尝试使用 apollo RESTDataSource 来包装我的休息 api。我需要将一些 header 传递给 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)}`);
}
我希望 header 包含“授权”。但它始终是空的。
上面代码的日志:
request 1: {"method":"POST","path":"partnerinvoices","body":{"command": "input","params":{},"headers":{}}
request 2: {"method":"POST","path":"partnerinvoices","body":{"command":"input","params":{},"headers":{}}
我可以毫无问题地覆盖 willSendRequest
方法中的主体和参数。
最佳答案
有几种方法可以实现这一点,
在扩展 RESTDataSource 的 Datasource
类中,在发出请求之前设置 header
willSendRequest(request) {
request.headers.set('Authorization', 'Bearer .....')
}
或作为数据源方法中的第三个参数(post、get、put、...)
this.post('endpoint', {}, { headers: { 'Authorization': 'Bearer ...' } })
关于javascript - 如何在 RESTDataSource 请求中包含 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55896080/