首页 > 解决方案 > Angular http 模块 - 发布标题

问题描述

在 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”。

我输入错误了吗?

标签: javascriptangularionic-framework

解决方案


我更喜欢这样的东西:

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

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

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


推荐阅读