clo*_*hoo 6 javascript apollo-server
我正在尝试使用 apollo RESTDataSource 来包装我的其余 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)}`);
}
Run Code Online (Sandbox Code Playgroud)
我期望标头包含“授权”。但它总是空的。
上述代码的日志:
request 1: {"method":"POST","path":"partnerinvoices","body":{"command": "input","params":{},"headers":{}}
request 2: {"method":"POST","path":"partnerinvoices","body":{"command":"input","params":{},"headers":{}}
Run Code Online (Sandbox Code Playgroud)
我可以willSendRequest毫无问题地覆盖方法中的主体和参数。
有几种方法可以实现这一点,
在Datasources扩展 RESTDataSource 的类中,在发出请求之前设置标头
willSendRequest(request) {
request.headers.set('Authorization', 'Bearer .....')
}
Run Code Online (Sandbox Code Playgroud)
或作为数据源方法中的第三个参数(post、get、put...)
this.post('endpoint', {}, { headers: { 'Authorization': 'Bearer ...' } })
Run Code Online (Sandbox Code Playgroud)