HttpHeader isn't correctly sent

为君一笑 提交于 2019-12-10 11:48:59

问题


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:

  1. 1st part of the 2nd call
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!