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);
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
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
});
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:
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
});
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
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
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
I am having an issue related to this new Http.Post of Ionic 3 and Angular 5. Got this issue on ipad App and I didn’t tried on browser.
I end up posting here after trying 7-8 hours.
My controller code:
this.api.post('index.php',
{'data': JSON.stringify(this.pendingRecords)}, {})
.subscribe( response => { console.log(response) };
My API Service code:
post(endpoint: string, body: any, reqOpts?: any) {
let headers = new HttpHeaders();
return this.http.post(this.url + '/' + endpoint, body,
{headers: headers.append('Content-Type', 'application/x-www-form-urlencoded')})
}
My Service headers:
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map, catchError } from 'rxjs/operators';
If there is any syntax mistakes, please ignore those and provide me any solution(this is code of several modified & trailed attempt).
My back end service is PHP. and it is working fine. I tested my backend service with hardcoded values. it is returning fine. Other wise Post is not at all taking any data. but, some how this Angular/common/http is not taking data to server.
I tried with JQuery sample code of $.POST, with browser extension to bypass CORS. even that is working fine in browser. Finally i don’t how to look at the requests in xcode like chrome network tab, to give you guys more information.
Update: I installed Charles and debugged this ionic app into ipad pro 9’ simulator to check what request is going. here is the result. Even though we are adding headers: application/x-www-urlencoded. it is somehow changing to application/json. is that any way reason because it is not sending data to php file