我正在尝试使用 Angular 6 中的 HttpHeader 进行后调用,并且我将 Content-Type 设置为 application/json。 但服务器获取的是 x-www-form-urlencoded 而不是 application/json 的 Content-Type。
服务.ts
myFunction(id: string, name: string, fields: string[]) {
const body = {
id: id,
name: name,
fields: fields
};
let headers = new HttpHeaders();
headers= headers.set('content-type', 'application/json');
return this.http.post(this.URL , body, {headers});
}
组件.ts
submit(){
this.myService.myFunction(this.id, this.form.value.name,
this.form.value.fields).subscribe((res:any) => {
console.log(this.form);
}, error => {
console.log(JSON.parse(error.error).errors);
})
}
您需要在选项中设置标题。
return this.http.post(this.URL , body, {headers : new HttpHeaders({ 'Content-Type': 'application/json' })});
只需使用
append
功能添加新标题,最后在选项上设置标题
尝试这样的事情,
let headers = new HttpHeaders();
headers= headers.append('content-type', 'application/json');
return this.http.post(this.URL, body, {headers : header});
如果不起作用尝试添加这样的标题,
let headers = new HttpHeaders({'content-type': 'application/json'});
希望有帮助。快乐编码:)