当使用Angular中的http模块(带有Ionic)进行发布请求时,我无法更改标题。 这是我的代码:
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”。
我打错了吗?
答案 0 :(得分:2)
我更喜欢这样的东西:
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
this.http.post<Foo>(this.apiUrl, body, httpOptions)
我也不认为需要对主体进行字符串化,只需将其作为“常规”对象传递