Http.post not sending data

Hi,

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';

@Injectable()
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 this.http.post(SERVER_URL + '/api/login.json', body, options)
			.toPromise()
			.then(response => response.json(), this.handleError);
	}

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

}
2 Likes

Because you need return data from then method.

return this.http.post(SERVER_URL + '/api/login.json', body, options)
	.toPromise()
	.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 http.post() 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

var_dump(json_decode(file_get_contents(“php://input”)));

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;
12 Likes

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’
email=example@gmail.com&password=abcd
solution:
your data like this:

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

this function convert your output like this : email=example@gmail.com&password=abcd
let postdata = this.formData(body);

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

Result : email=example@gmail.com&password=abcd

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

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

Result : email=example@gmail.com&password=abcd

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

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

}

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 
	});
5 Likes

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]);
    }).join('&');
  }

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

Hope this helps someone

3 Likes

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

print_r($_REQUEST[‘name’]);

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      = "http://192.168.2.31/fetch/public/api/user/register";

this.http.post(url,body,options)
        .subscribe((data) => {
          console.log(JSON.stringify(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”);

step3:
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({
‘NDAPI-Key’: ‘XXXXXXXXX’,
‘NDAPI-Host’: ‘XXXXXXXXX’
});
let options = new RequestOptions({ headers: headers });

var token = this._WSToken;

this.http.post('/localhost' + '/' + controle + '/' + metodo, { token, endereco, cliente }, options)
  .map(res => res.json())
  .subscribe(data => {
    endereco = data;
    console.log(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: