415 Unsupported media type; Angular2 API

I am new to angular 2, and I ran into a problem that I cannot find a solution to: When I try to send a message from angular 2 to the API, I get - 415 unsupported media type.

Angular 2 code:

onSubmit(value: any) { // console.log(value.message); let headers = new Headers({ 'Content-Type': 'application/json'}); let options = new RequestOptions({ headers: headers }); let creds = 'statusuknown'; let body = JSON.stringify(creds); this.http.post('http://localhost:1318/api/ActionItem', creds) .subscribe( () => {console.log('Success')}, err => {console.error(err)} ); } 

And my controller code:

  // POST api/actionitem [HttpPost] public ActionItem Post( [FromBody]string str)// _id, string _status) { ActionItem item = new ActionItem( 313, str); return item; } 

when I change the controller code so as not to receive data from the body, it works, but refers to NULL.

My screenshot of the API call: enter image description here Please help and let me know if more information is needed.

+7
source share
3 answers

enter image description here You defined the headers but did not use It. Change your code to

 this.http.post('http://localhost:1318/api/ActionItem', body, options).map(response => response.json()) .subscribe( () => {console.log('Success')} ); 
+1
source

use the header and body also in the http request. in cread use onSubmit function parameter value.

use the following code

 let creds=JSON.Stringify(value); this.http.post('http://localhost:1318/api/ActionItem', creds, options) .map((res: Response) => res.json()).subscribe(res => { this.result = res; console.log(this.result); }); 
0
source
 I have personally found that when the parameters, or model you pass to the service are different from one at the api parameter, you get this error. 
0
source

Source: https://habr.com/ru/post/1266859/


All Articles