使用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”.
我打错了吗?
最佳答案
我更喜欢这样的东西:
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
this.http.post<Foo>(this.apiUrl,body,httpOptions)
另外,我不认为需要对主体进行字符串化,只需将其作为“正常”对象传递即可