9
votes

i am new to angular 2 and i'm facing a problem which i cant find a solution: When i try to post from angular 2 to 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 to not get data from body it works but refers NULL.

My API call screenshot: enter image description here Please help & let me know if more details needed.

2
The error message is pretty self-descriptive: You send JSON and the server tells you "I don't support JSON"a better oliver
@zeroflagL that makes sense, although im not sure ,when i use POSTMAN to post to my api it goes thru and return the value i need. how do i make my api support JSON?Orenger
I assume you don't set a Content-Type header when you use Postman. You only send a string in your example, so you actually don't need JSON. You can send creds directly.a better oliver
@zeroflagL i do set content-type when i use postman , otherwise it doesn't work, looks like it has something to do with my localhost use. i was informed to try post using a server and it will work! exactly how postman works!Orenger
I see. Then the problem could be CORS. That would mean that the server needs additional (or a different) configuration.a better oliver

2 Answers

1
votes

enter image description hereYou defined headers, but didn't use it. Change your code to

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

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

use 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);
     });