【问题标题】:Ionic 4 - Trying to adding headers to post - post call not accepting optionsIonic 4 - 尝试将标题添加到 post - post call 不接受选项
【发布时间】:2020-02-26 20:13:37
【问题描述】:

我正在尝试在我的帖子中发送标题,但我似乎无法为选项获取有效值。

  sendPostRequest() {
    let token = this.storage.get('ACCESS_TOKEN');
    var headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Bearer ' + token);
    headers.append('responseType', 'text');
    let postData = this.signatureForm.value;
    this.httpClient.post("http://localhost:3000/signature", postData, { headers: headers })
      .subscribe(data => {
        this.presentToast();
      }, error => {
    });
  }

I'm getting an error in my editor on ```{ headers: headers }```
Error message is:

没有重载匹配这个调用。最后一个重载给出了以下 错误。 类型 'Headers' 不可分配给类型 'HttpHeaders | { [标题:字符串]:字符串 |细绳[]; }'。 类型 'Headers' 不可分配给类型 '{ [header: string]: string |细绳[]; }'。 'Headers'.ts(2769) http.d.ts(2431, 9) 类型中缺少索引签名:预期类型来自属性'headers' 这是在类型 '{ headers?: HttpHeaders | { [标题: 字符串]:字符串 |细绳[]; };观察?:“身体”;参数?: HttpParams | { [参数:字符串]:字符串 |细绳[]; };报告进度?:布尔值; 响应类型?:“json”; withCredentials?:布尔值; }' http.d.ts(2430, 5): 最后一个重载在这里声明。

【问题讨论】:

    标签: angular ionic4


    【解决方案1】:

    试试这样:

    const headers = new HttpHeaders().set('Content-Type', 'application/json')
                                     .set('Accept', 'application/json')
                                     .set('responseType', 'text')
                                     .set('Authorization',  'Bearer ' + token);
    
    this.httpClient.post("http://localhost:3000/signature", postData, { headers: headers })
      .subscribe(data => {
        this.presentToast();
      }, error => {
    });
    

    【讨论】:

    • 它正在发送标头值,但是对于我的令牌,我只是得到“授权”:“Bearer [object Promise]”
    • show console.log(token),我猜这是一个对象,必须从中取出字符串
    • 我认为它应该正常工作,我在标题中获取值。
    【解决方案2】:

    你正在使用接口Headers 你需要使用HttpHeaders from @angular/common/http'

    例子:

    import { HttpHeaders } from '@angular/common/http';

    var headers = new HttpHeaders();
    headers.append('Accept', 'application/json'); 
    //append more stuff
    

    【讨论】:

      【解决方案3】:

      它可以在httpOptions 内。您可以修改标题,例如,

      const httpOptions = {
            headers: new HttpHeaders({
               'Accept': 'application/json '
               'Content-Type': 'application/json',
               'responseType': 'text',
               'Authorization': 'Bearer ' + token  
            });
          }
      
      
      
      this.httpClient.post("http://localhost:3000/signature", postData, httpOptions)
            .subscribe(data => {
              this.presentToast();
            }, error => {
          });
      

      【讨论】:

        猜你喜欢
        • 2016-04-30
        • 2017-11-24
        • 2013-10-18
        • 2019-04-06
        • 2021-09-01
        • 2015-07-05
        • 2019-08-28
        • 1970-01-01
        • 2014-12-02
        相关资源
        最近更新 更多