I'm trying to use apollo RESTDataSource to wrap my rest api. I need to pass some headers to the api call.
I'm following the example from the docs:
This is my code:
willSendRequest(request: RequestOptions) {
console.log(`request 1: ${JSON.stringify(request)}`);
request.headers.set('Authorization', this.context.authorization);
console.log(`request 2: ${JSON.stringify(request)}`);
}
I'm expecting the headers to contain 'Authorization'. But it's always empty.
The log from the above code:
request 1: {"method":"POST","path":"partnerinvoices","body":{"mand": "input","params":{},"headers":{}}
request 2: {"method":"POST","path":"partnerinvoices","body":{"mand":"input","params":{},"headers":{}}
I can override body and params in willSendRequest
method without any problem.
I'm trying to use apollo RESTDataSource to wrap my rest api. I need to pass some headers to the api call.
I'm following the example from the docs: https://www.apollographql./docs/apollo-server/features/data-sources#intercepting-fetches
This is my code:
willSendRequest(request: RequestOptions) {
console.log(`request 1: ${JSON.stringify(request)}`);
request.headers.set('Authorization', this.context.authorization);
console.log(`request 2: ${JSON.stringify(request)}`);
}
I'm expecting the headers to contain 'Authorization'. But it's always empty.
The log from the above code:
request 1: {"method":"POST","path":"partnerinvoices","body":{"mand": "input","params":{},"headers":{}}
request 2: {"method":"POST","path":"partnerinvoices","body":{"mand":"input","params":{},"headers":{}}
I can override body and params in willSendRequest
method without any problem.
3 Answers
Reset to default 6There are few ways that you could implement this,
within your Datasources
class that extends RESTDataSource set the headers before request is being made
willSendRequest(request) {
request.headers.set('Authorization', 'Bearer .....')
}
or as a third argument in the datasource method (post, get, put, ...)
this.post('endpoint', {}, { headers: { 'Authorization': 'Bearer ...' } })
It is super important, if you are using Typescript, that you match the original signature of the willSendRequest
method:
protected willSendRequest?(request: RequestOptions): ValueOrPromise<void>;
(Link to the docs)
So, make sure the method looks like this:
protected willSendRequest?(request: RequestOptions): ValueOrPromise<void> {
request.headers.set("Authorization", this.context.authorization);
}
You need to use request.headers.get('Authorization')
to get your desired data. Using JSON.stringify
will not give you the headers values as it is not a object literal.
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')}`);
}