415 Unsupported Media Type; Angular2 to API

三世轮回 提交于 2020-01-24 02:28:06

问题


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: Please help & let me know if more details needed.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/43473474/415-unsupported-media-type-angular2-to-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!