Check out our Angular Book Series.

How do I send JSON to a Server in Angular 2+?

I have a lot more trouble answering Angular questions on StackOverflow than I did answering Flex questions. The bulk of Angular problems seem to come from integrating different systems and libraries together. But, every once in a while I see a question that I seem to be the perfect person to answer. This question is about Sending JSON from Angular to PHP. I wrote a book about that.

When sending JSON to PHP--or Java or ColdFusion or any server side tech--you need to be sure to set the headers to application/json.

If you are using Angular 2, this is how you do it:

let optionHeaders : Headers = new Headers();
optionHeaders.append('Content-Type', 'application/json');
let options: RequestOptions = new RequestOptions({headers:optionHeaders});
this.http.post(serverEndPoint, JSONPayload,options);

We create an instance of a RequestOptions object, and add the Headers onto it. The RequestOptions object is sent as part of your server request, in this case using a post() method. This is all part of the now deprecated Http library.

Angular 5 introduced the new HttpClient library, which does things a bit differently:

let options : Object;
let optionHeaders : HttpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
options = {headers:optionHeaders};
this.http.post(serverEndPoint, JSONPayload,options);

You create a generic options object, and add an HttpHeaders() instance inside of it. Send that as the options argument to the http method, also a post().

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.