【问题标题】:Angular http module - post headersAngular http 模块 - 发布标题
【发布时间】:2019-07-18 06:57:48
【问题描述】:

在 Angular(使用 Ionic)中使用 http 模块进行发布请求时,我无法更改标头。 这是我的代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const apiUrl = "https://webhook.site/c2d56330-84d4-47cf-9f98-472f7eac8000";

@Injectable({
  providedIn: 'root'
})
export class APIService {

  constructor(private http: HttpClient) { }

  getToken(){
    var body = {
      'data1': 'data2',
      'somedata3': 'data4',
  };
  let headers = new HttpHeaders().append('Content-Type', 'application/json');

  this.http.post(apiUrl, JSON.stringify(body), {headers}).subscribe(data =>
    console.log(data));

  console.log(headers.get('Content-Type')); //return 'application/json'
  }
}

一切正常,但它仍然发送标头“content-type: text/plain”而不是“content-type: application/json”。

是不是我打错字了?

【问题讨论】:

标签: javascript angular ionic-framework


【解决方案1】:

我更喜欢这样的东西:

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

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};
this.http.post<Foo>(this.apiUrl, body, httpOptions)

另外我认为不需要对主体进行字符串化,只需将其作为“普通”对象传递

【讨论】:

  • 感谢您的回复。如果我在没有 JSON.stringify 的情况下传递正文,它将只发送没有任何数据的空请求。
猜你喜欢
  • 2018-10-02
  • 2018-08-29
  • 2017-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 2018-09-10
相关资源
最近更新 更多