Orenger
Orenger

Reputation: 172

415 Unsupported Media Type; Angular2 to API

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.

Upvotes: 9

Views: 16793

Answers (2)

Jeetendra negi
Jeetendra negi

Reputation: 197

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

Upvotes: 0

Victor Bredihin
Victor Bredihin

Reputation: 2360

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

Upvotes: 1

Related Questions