简体   繁体   English

Angular 6:无法正确设置 http Header 的 Content-Type

[英]Angular 6: Unable to set Content-Type of http Header correctly

I'm trying to make a post call using HttpHeader in angular 6 And I set Content-Type to application/json.我正在尝试在 Angular 6 中使用 HttpHeader 进行后期调用,并且我将 Content-Type 设置为 application/json。 But the server get x-www-form-urlencoded instead of application/json for Content-Type.但是服务器为 Content-Type 获取 x-www-form-urlencoded 而不是 application/json。

service.ts服务.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组件.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' })});

Just use append function to add new headers and finally set the headers on options只需使用append函数添加新标题,最后在选项上设置标题

Try something like this尝试这样的事情

let header = new HttpHeaders();
headers= headers.append('content-type', 'application/json');
return this.http.post(this.URL , body, {headers : header});

If it doesn't work try to add header like this如果它不起作用,请尝试添加这样的标题

let header = new HttpHeaders({'content-type': 'application/json'});

Hope it helps - happy coding :)希望它有所帮助 - 快乐编码:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM