1

Im trying to send an http.post request from my angular app to the rest server using the following code:

I'm using: import { Http } from '@angular/http';

let headers = new Headers();
  headers.append('Content-Type', 'application/json');
let data: string = 'wing,wheel';
this.http.post('http://172.16.2.209:3000/api/AddPartList?access_token=xxxxxxxxxxxx',{headers: headers},data)

But I keep getting the error Response with status: 422 Unprocessable Entity for URL

The curl command for what I want to do is:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \ 
   "$class": "org.blockaviation.AddPartList", \ 
   "partListId": "1", \ 
   "partList": "wing,wheel", \ 
   "plane": "resource:org.blockaviation.Plane#Plane_001" \ 
   \ 
 }' 'http://172.16.2.209:3000/api/AddPartList'

Does anyone know what I'm doing wrong or how to do this properly?

Simon Mullaney
  • 447
  • 2
  • 5
  • 21
  • Your `post` parameters are in the wrong order. It goes URL, data, then options (like headers). – R. Richards Feb 12 '18 at 12:58
  • I have seen that but if I do: `this.http.post('http://172.16.2.209:3000/api/AddPartList?access_token=xxxxxxxxxxxx',data,{headers: headers})` I get the following error:Argument of type '{ headers: Headers; }' is not assignable to parameter of type 'RequestOptionsArgs'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but they are unrelated. – Simon Mullaney Feb 12 '18 at 13:03
  • You can find an answer for that issue [here](https://stackoverflow.com/questions/34475523/how-to-pass-url-arguments-query-string-to-a-http-request-on-angular). – R. Richards Feb 12 '18 at 13:10
  • Got it working thank you all so much for your answers :) – Simon Mullaney Feb 12 '18 at 15:26

2 Answers2

2

You should put your headers inside a RequestOptions object like this:

import { Http, Headers, RequestOptions } from '@angular/http';

private requestOptions = new RequestOptions({
    headers: new Headers({
        'Content-Type': 'application/json'
    })
});

this.http.post(this.url, data, this.requestOptions);
Juan
  • 2,024
  • 3
  • 17
  • 36
2

If you are using something like json-server

import { Http, Headers, RequestOptions } from '@angular/http';

const headers = new Headers({'Content-Type': 'application/json'});
const options = new RequestOptions({headers: headers});

this.http.post(this.url, JSON.stringify(data), options)...
Kirubel
  • 1,461
  • 1
  • 14
  • 33