HttpHeader未正确发送 [英] HttpHeader isn't correctly sent
问题描述
我根据本指南编码: https:/ /angular.io/guide/http#configuring-other-parts-of-the-request 。
I am coding according to this guide: https://angular.io/guide/http#configuring-other-parts-of-the-request.
我的代码如下:
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 显示此值:
header:{normalizedNames:[],lazyUpdate:[{name:api-key,value:JEFE_HHHABBBJJJXXX, op:s}],headers:[],lazyInit:{normalizedNames:[],lazyUpdate:null,headers:[]}}
JSON.stringify shows this value:
header:{"normalizedNames":[],"lazyUpdate":[{"name":"api-key","value":"JEFE_HHHABBBJJJXXX","op":"s"}],"headers":[],"lazyInit":{"normalizedNames":[],"lazyUpdate":null,"headers":[]}}
但是服务器没有收到'api-key'值。
but the server is not receiving the 'api-key' value.
我执行了POSTMAN相同的值和服务器正确接收'api-key'值。
I executed POSTMAN with the same value and the server correctly received the 'api-key' value.
我做错了什么?
UPDATE
此快照表示第一次调用'getMenuOptions'方法:首次调用服务器
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
正如您在第二个电话的第二部分看到的那样,包含'api'的标题-key'值在'lazyUpdate'对象中发送。
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.
推荐答案
问题在于你的<$ c $的实现c> getMenuOptions 方法。
您不尊重 HttpClient
中 post
方法的定义。
The problem is in the implementation of your getMenuOptions
method.
Your are not respecting the definition of the post
method from the HttpClient
.
它应该是这样的:
http
.post('/api/items/add', body, {
headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
}).
其中:
1st arguement: endpoint
2nd: request body
3rd: an object with the request config
目前,您正在将headers对象作为第二个参数传递,并且不提供任何配置对象(第三个参数),因此您的请求自然不会按预期运行。
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.
这篇关于HttpHeader未正确发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!