not sending data


I’m trying to do a http post using the http module in Angular 2.

The POST request hits the server OK (CORS is all taken care of) but no post data is received. Any idea what I might be doing wrong?

This is my code:

import {Injectable} from 'angular2/core';
import {Http, Headers, RequestOptions} from 'angular2/http';
import 'rxjs/Rx';

const SERVER_URL = 'http://MY-SERVER.COM';

export class UserData {

	constructor(private http: Http) {

	login(email, password) {
		let headers = new Headers({
			'Content-Type': 'application/json'
		let options = new RequestOptions({
			headers: headers
		let body = JSON.stringify({
			email: email,
			password: password
		return + '/api/login.json', body, options)
			.then(response => response.json(), this.handleError);

	handleError(error) {
		return error.json().message || 'Server error, please try again later';


Because you need return data from then method.

return + '/api/login.json', body, options)
	.then(response => { return response.json() }, this.handleError);

Hi Xr0master,

the returning of the data is not the problem (yet, anyway ;-)).

On the server (I use PHP) I log $_POST to a file, and it is always an empty array when using in angular 2.

Oh, but you send json and it’s not post data. Of course PHP $_POST is empty )

You could get json from stream


or send post :slight_smile:

Well I want to send a regular post request with post data - any idea how I might do that?

I’m sorry, I did not know that you are banned in Google.

If I remember, you need use something like this:

let body = new FormData();
body.append('email', email);
body.append('password', password);

let headers = new Headers({
  'Content-Type': undefined
1 Like

Try this way:

		let headers = new Headers({
			'Content-Type': 'application/x-www-form-urlencoded'
		let options = new RequestOptions({
			headers: headers
		// TODO: Encode the values using encodeURIComponent().
		let body = 'email=' + email + '&password=' + password;

Thank you, lignatov! That did the trick!

It is very verbose, compared to how we did things in angular 1, think that might change before final release?

I don’t know, the Http implementation for Angular 2 is still a work in progress, so there could be some changes until the final release. However this is just a utility class, i.e. you could make some helper methods in your service class that could abstract the verbosity. The following article might be helpful:

1 Like

PHP method POST accept this format ‘Content-Type’ : 'application/x-www-form-urlencoded’
your data like this:

let body = JSON.stringify({ email : "", password : “abcd” });

this function convert your output like this :
let postdata = this.formData(body);

console.log("Result : " + postdata );

Result :

you can use this function with your form
let postdata = formData(this.loginForm.value);

console.log("Result : " + postdata );

Result :

//function formData convert data to ‘Content-Type’ : ‘application/x-www-form-urlencoded’

  return Object.keys(myFormData).map(function(key){
  return encodeURIComponent(key) + '=' + encodeURIComponent(myFormData[key]);


please change your header like this

let headers = new Headers({
// ‘Content-Type’: ‘application/json’ // This is your old content type

            'Content-Type' : 'application/x-www-form-urlencoded' // change to like this 

The function is a great start to make things a little bit easier.

Essentially use MPUNIA code above but don’t JSON.stringify your object first. Just toss in the object to the function like below.

  //Example usage of below function
  let body = this.jsonToURLEncoded({ username: usrnme, password: psswrd });

  //convert a json object to the url encoded format of key=value&anotherkye=anothervalue
  private jsonToURLEncoded(jsonString){
    return Object.keys(jsonString).map(function(key){
      return encodeURIComponent(key) + '=' + encodeURIComponent(jsonString[key]);

Full credit to MPUNiA. Just renamed the function to something I thought was a little more legible.

Hope this helps someone


This does the trick spent more than 5hours on this until this tutorial…

Try this One… it will be work fine…

this.token = sessionStorage.getItem(‘token’);
this.body = ‘bearer’ + this.token;

  let JsonString: any;
  var i = JSON.stringify({
    Id: this.localId, DeliverymanId: this.localDeliverymanId, Image: Sign, Qty: this.qty, Remarks: this.remarks, Status: this.Status,
    Photo: this.Photo64, Reason: this.localReasonId, BusinessUnitId: this.BussinessUnitId, CreatedUserId:  this.UserId, ModifiedUserId: this.UserId

  let headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.body });

  let options = new RequestOptions({ headers: headers });

  this.http.put(localStorage.getItem("FirstTimeUrl") + '/api/JobsAPI', i, options).map(res => res.json()).subscribe(data => {

Thank you for all your solutions so far!
Unfortunately there is still nothing ending up in my database. Can please provide someone the PHP-part to fetch those post-Data?

I’m using:
$postdata = file_get_contents(“php://input”);
if (isset($postdata)) {
$request = json_decode($postdata);
$user = $request->user;
$data = $request->data;

OK, a simple
$user = $_POST['user'];
did it :wink:

Hey, man! I’m having the same issue and I’m newbie to ionic and angular 2. Could explain your solution for dummies?

in php


from angular js this is my code

 let body     : string   = '{"name" : "value"}',
         type: 'application/json',
          headers  : any      = new Headers({ 'Content-Type': type}),
          options  : any      = new RequestOptions({ headers: headers }),
          url      : any      = "";,body,options)
        .subscribe((data) => {

but I am getting error like undefined $_REQUEST[‘name’]

Hi, i also faced the same problem sometime when I was trying to send data to the serve, here is what I did now it works fine.
step 1:
create a formData object and append the data you want to send on it.
let body = new FormData();
body.append("key ", "value ");
// the key is what you will reference in your server code ie
$name = $this->input->post(“key”); if using codeigniter ot $_POST[“key”];

step 2:
Set your headers as well
let headers = new Headers(); // import the headers from the '@angular/http’
headers.append(“Content-Type”, “application/json”);

Make sure you subscribe to your post request.

step 4:
Server side make sure to add the the access control allow origin headers. like this
header(“Access-Control-Allow-Origin: *”);

thanks and regards.

Galera, estou com um problema no envio de post: Sempre que vou enviar um post:
let headers = new Headers({
let options = new RequestOptions({ headers: headers });

var token = this._WSToken;'/localhost' + '/' + controle + '/' + metodo, { token, endereco, cliente }, options)
  .map(res => res.json())
  .subscribe(data => {
    endereco = data;
  }, error => {
    console.log("Oooops!" + error);

esse é o meu metodo post para enviar os dados, mas quando chega no webservice rest para ele realizar a conversão:
public function create(Request $request) {
return json_decode($request->input(‘cliente’));

ele apresenta um erro interno, mas quando envio os json pela aplicação android mesmo nativa utilizando o retrofit ele recebe e converte normal sem problemas.
Gostaria de saber se alguém já passou pela mesma situação, estou há muito tempo tentando resolver isso… Obrigado! Sei que não é em inglês a pergunta mas se alguém pudesse ajudar ficaria muito grato mesmo.

hi nikhil ,
your given url is working fine?

Thank you xr0master this way work for me :+1: