9

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.

Orenger
  • 172
  • 1
  • 2
  • 11
  • The error message is pretty self-descriptive: You send JSON and the server tells you _"I don't support JSON"_ – a better oliver Apr 19 '17 at 08:11
  • @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 Apr 19 '17 at 11:45
  • 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 Apr 19 '17 at 15:10
  • @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 Apr 20 '17 at 12:51
  • I see. Then the problem could be CORS. That would mean that the server needs additional (or a different) configuration. – a better oliver Apr 20 '17 at 13:57
  • as for now that seems to be the problem, i will use server with iis and will post afterwards – Orenger Apr 20 '17 at 13:58

2 Answers2

1

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')}
      );
Victor Bredihin
  • 2,220
  • 21
  • 30
0

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);
     });
Jeetendra negi
  • 187
  • 2
  • 9