我正在尝试使用angular 6中的HttpHeader进行post调用,并将Content-Type设置为应用程序/json。但是服务器得到的是x-www-form-urlencoded而不是Content-Type的application/json。
service.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});
}
component.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);
})
}
发布于 2018-12-05 02:09:06
您需要在option中设置headers。
return this.http.post(this.URL , body, {headers : new HttpHeaders({ 'Content-Type': 'application/json' })});
发布于 2018-12-05 02:27:47
只需使用append
函数添加新的标头,最后在选项上设置标头
试试这样的东西
let header = new HttpHeaders();
headers= headers.append('content-type', 'application/json');
return this.http.post(this.URL , body, {headers : header});
如果不起作用,尝试添加标题,如下所示
let header = new HttpHeaders({'content-type': 'application/json'});
希望它能帮上忙--快乐编码:)
https://stackoverflow.com/questions/53618872
复制相似问题