问题
I am coding according to this guide: https://angular.io/guide/http#configuring-other-parts-of-the-request.
My code is the following:
loadMenuOptions(): void {
console.log('this.currentApiKey |' + this.currentApiKey);
let header = new HttpHeaders();
header = header.set('api-key', this.currentApiKey);
this.commonService. getMenuOptions(MENU_OPTIONS, header).subscribe(respuesta => this.setMenuOptions(respuesta));
}
The following code is when I send this object to the server:
getMenuOptions(endPoint: string, header: HttpHeaders): Observable<OptionsResponse> {
console.log('header:' + JSON.stringify(header));
return this.http.get<OptionsResponse>(endPoint, header)
.pipe(
tap(res => this.log('getMenuOptions | status | ' + res.header.status)),
catchError(this.handleError('getMenuOptions', null)));
}
JSON.stringify shows this value:
header:{"normalizedNames":[],"lazyUpdate":[{"name":"api-key","value":"JEFE_HHHABBBJJJXXX","op":"s"}],"headers":[],"lazyInit":{"normalizedNames":[],"lazyUpdate":null,"headers":[]}}
but the server is not receiving the 'api-key' value.
I executed POSTMAN with the same value and the server correctly received the 'api-key' value.
What am I doing wrong?
UPDATE
This snapshot represents the first time that is invoked the 'getMenuOptions' method: first call to the server
This screenshot belongs to the second call to the server:
- 1st part of the 2nd call
- 2nd part of the 2nd call
As you are seeing at the 2nd part of the 2nd call, the header which contains the 'api-key' value is sent inside a 'lazyUpdate' object.
回答1:
The problem is in the implementation of your getMenuOptions
method.
Your are not respecting the definition of the post
method from the HttpClient
.
It should be like this:
http
.post('/api/items/add', body, {
headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
}).
Where:
1st arguement: endpoint
2nd: request body
3rd: an object with the request config
Currently you are passing the headers object as 2nd argument and giving no configuration object (3rd argument), so its natural that your request isn't behaving as expected.
来源:https://stackoverflow.com/questions/47884319/httpheader-isnt-correctly-sent