-1

In angular 4, How can I post just JSON as data?

Currently, my post code is:

let options = {
    headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded)
};

let urlSearchParams = new URLSearchParams();

urlSearchParams.append('key', 'value');

let bodyString = urlSearchParams.toString();

return this.http.post(api, bodyString, options);

As you can see I am using application/x-www-form-urlencoded and URLSearchParams before post. (which is working)

I think there will be a way to use just JSON. (e.g. this.http.post(api, MY_JSON))

I have tried new HttpHeaders().set('Content-Type', 'application/json') but no luck.

The below is what I want :

let options = {
    headers: new HttpHeaders().set('Content-Type', 'application/json)
};

return this.http.post(api, MY_JSON, options);

If I post like the above, everything is correctly posted but no reaction from the server.

Should I check back-end?

Téwa
  • 1,184
  • 2
  • 13
  • 19
  • URL search parameters are for query strings, e.g. `?key=value`, *in the URL*. What exactly should the *payload*, the body of the request, be? You *can* pass arrays and objects to post and have them serialised. – jonrsharpe Sep 27 '17 at 13:56
  • If you are using the json content-type header, you can pass in the json object as the 2nd parameter of .post() – LLai Sep 27 '17 at 13:58
  • @jonrsharpe I added more explain. I know that URLSearchParams is for query string. However, seems it's only way to post in angular so far for me. If there is no problem in the 'The below is what I want' code, should I check back-end? – Téwa Sep 27 '17 at 14:14
  • Well if you look at the request in tests or the browser, does it have the structure you expect? Yes, I think you need to check the server. – jonrsharpe Sep 27 '17 at 14:15
  • @jonrsharpe Yes I see the structure what I expect when i post in the network tab in Chrome. Just I wasn't sure if I'm doing anything wrong in front-end. Thanks. – Téwa Sep 27 '17 at 14:18

1 Answers1

0

It was back-end configuration.

In symfony3(PHP), simply run json_decode() to get json from front-end.

Téwa
  • 1,184
  • 2
  • 13
  • 19