Ionic2 Post Services

How can you post data that requires a JSON object as the parameter (parameters if you think about it).

let var url = ...
let jsonObject = ...
let headers = ....
http.post(url, JSON.stringify(jsonObject), {headers: headers})
    .subscribe((next)=>console.log(next))

So after, how do I work with the data?

However you need to inside the subscribe onnext block.

http.post(url, JSON.stringify(jsonObject), {headers: headers})
  .map((response) => response.json())
  .subscribe((json) => {console.log(json)});

Thanks, you are really helping me out and I appreciate it. However, I have a little problem, anytime I post data (the server requests a JSON object), I get an Error 400 (which I found out to mean that the server could not receive the data in the format it wanted).
I set some headers and got a new error; Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote
resource at http://www.testwebpage.com. (Reason: CORS preflight
channel did not succeed).
Can someone please review my code and see what I did wrong?

var url = “http://www.testpage.com”;
var headers = new Headers({
‘Content-Type’: ‘application/json’,
‘Accept’: ‘application/json’
});
var data = ‘email:kenneth.cross95@gmail.com, password:123456a’;
this.http.post(url, JSON.stringify({data}), {headers: headers}).subscribe(
data => {console.log(“Worked”)},
error => {console.log(“Did not work”)},
);

1 Like

are you found solution for this?

Your data doesn’t seems to be a valid JSON object.

var data = 'email:kenneth.cross95@gmail.com, password:123456a';

You can check your json object with JSONLint

Correct json format is

{ "email": "kenneth.cross95@gmail.com", "password": "123456a" }

And you could remove JSON.stringify() function i think.