【问题标题】:HttpHeader isn't correctly sentHttpHeader 未正确发送
【发布时间】:2022-02-15 14:45:49
【问题描述】:

我正在根据本指南编码: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));
  }

以下代码是我将这个对象发送到服务器时:

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":[]}}

但服务器没有收到“api-key”值。

我用相同的值执行了 POSTMAN,服务器正确接收到了 'api-key' 值。

我做错了什么?

更新

此快照表示第一次调用 'getMenuOptions' 方法:first call to the server

此截图属于对服务器的第二次调用:

  1. 1st part of the 2nd call
  2. 2nd part of the 2nd call

正如您在第二次调用的第二部分看到的那样,包含“api-key”值的标头在“lazyUpdate”对象中发送。

【问题讨论】:

  • HttpHeaders 是不可变对象,所以你必须参考这个answer
  • @Aravind,如果你看到我的代码,你会看到我创建了一个新的标头对象。
  • 能否添加浏览器网络开发工具中记录的请求/响应标头?
  • @Jota.Toledo,我更新了我的帖子。 :)
  • 请将您的源代码添加到您的问题中,而不是图片中

标签: angular http-headers angular-httpclient


【解决方案1】:

问题在于您的getMenuOptions 方法的实现。 您不尊重HttpClientpost 方法的定义。

应该是这样的:

http
  .post('/api/items/add', body, {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
  }).

地点:

1st argument: endpoint
2nd: request body
3rd: an object with the request config

目前,您将标头对象作为第二个参数传递,并且没有提供配置对象(第三个参数),因此您的请求没有按预期运行是很自然的。

【讨论】:

  • 也许不是“post”方法(因为我不向服务器发送任何正文)而是“get”方法。我会试试这个。谢谢,@Jota.Toledo
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 2013-04-26
  • 2012-07-28
  • 2020-07-06
  • 2015-07-07
  • 2011-01-08
相关资源
最近更新 更多