I've been trying to figure this out for almost a day, with no luck.
I have a simple http.post request:
import { Component } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Component({
selector: 'SendPost',
})
export class SendPostComponent {
constructor(
private http:Http,
) {}
private urlPost:string = 'www.mydomain.com/api/order.php'
private addToBasket() {
var data = {
foo: "bar",
foo1: "another"
}
var postData = JSON.stringify(data);
let headers = new Headers({'Content-Type': 'application/json'}); //x-www-form-urlencoded
headers.append('Access-Control-Allow-Methods', "GET, POST, OPTIONS");
let options = new RequestOptions({ headers: headers });
this.http.post(
this.urlPost,
postData,
options
)
.toPromise()
.then((res) => {this.extractData(res)});
}
private extractData(res: Response) {
console.log('extractData:', res);
}
}
I striped the API endpoint to absolute minimum: no .htacces, just the php file this simple code:
<?php print_r(json_encode($_REQUEST)); die; ?>
I keep getting an empty array in return. However, if I change the code like this:
var data2 = 'foo=bar&foo1=another'
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
Then the $_REQUEST objects gets my data. What am I missing?
PHP $_REQUEST is:
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE
and $_POST
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
PHP can't parse "application/json" data, the workaround is php wrapper, by using "file_get_contents('php://input')" you can fetch the data from request entity body in this way:
$body = file_get_contents('php://input');
$data = json_decode($body);
print_r($data); // here is what you need
Related
i try to send post request in flutter app like
static Future<List<dynamic>?> postData(data) async {
var body = json.encode(data);
Map<String, String> headers = {"Content-Type": "application/json"};
var url = Uri.http(Config.api, Config.endPoint);
var response = await client.post(url, headers: headers, body: body);
if (response.statusCode == 201) {
var data = jsonDecode(response.body);
return data;
}
return null;
}
this is data was sent
Map data = {
'database': 'school_control_ykt',
'table': 'tablets_helper',
'place': place,
'reason': reason,
'teacher': teacher,
'name': name,
'id_group': id_group
};
postData(data);
but in server side (php) $_POST are empty
i wanna know why $_POST are empty when a send the request in flutter app but in Postman request is send successfully and $_POST have data
enter image description here
Use MultipartRequest as API expect multipart/form-data. Something like this:
var request = MultipartRequest('POST', uri)
..fields = data
var response = await request.send();
I already developed ionic 4 in my Mac. When trying to improve an app in ionic 3, my http.post (angular) calls in php is received as GET ($ _SERVER ['REQUEST_METHOD']). I discovered that my parameters are not being recognized in php.
* I read the other posts and none solved my problem
Thank you!
import { Http , Headers, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
let parametros = JSON.stringify({
idtApostador: localStorage.getItem("idtApostador"),
});
let headers = new Headers(
{
'Content-Type' : 'application/json'
});
let options = new RequestOptions({ headers: headers });
return new Promise(resolve => {
this.http.post(url, parametros, options)
.timeout(15000)
.subscribe(data => {
})
})
I ask, I answer. :)
https instead of http.
Use
import { HttpClient } from '#angular/common/http';
Instead of HTTP
I have an "api rest" that I created in PHP, the service returns a JSON with the parameters of "header", "body", "get", "pos", which comes to receive without any type of validation.
Now I have created a service in angular to connect with the "api rest", all right up there, the problem I have is that I want to send a parameter as a "BODY", but I do not know how, I have been investigating but I have not found a shape.
Is it possible to send the "body" via HttpClient.get()?
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ServicioService {
constructor(private http: HttpClient) { }
getQuery(query: string){
const url = `http://localhost:8080/servicio/`;
const headers = new HttpHeaders({
'Authorization': 'Bearer BQAiaibx-we0RSlZFN29B5TPF4t6egxbuuEsc5ZYZhpamHUhImd5'
});
const params = new HttpParams()
.set('page', '2')
.append('page', '3')
.set('sort', 'abc');
return this.http.get (url, { params, headers});
}
getNewReleases(){
return this.getQuery("")
.pipe( map((data: any) => {
return data;
}));
}
}
A GET request does not have a body.
You should use POST or PUT.
You can read here a little bit about the http methods.
About the GET: The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect
So, it would be wrong to send a body because a GET method should not change anything.
Angular 4.4.4
This is my app component
constructor(
private http: HttpClient,
)
this.http.post('/api.php', {name, age}).subscribe(data => {
console.log(data);
});
api.php -> exit(json_encode($_POST));
Don't receive any data in $_POST
return [];
(let xmlRequest = new XMLHttpRequest();
....
works fine)
I try set header
let headers = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8');
not work
Sorry for this question but I spent 1 day and still could not find solution.
ps. client and server has same origin.
You need to put your parameters into a FormData Object on the Angular side.
const params = new FormData();
params.append('para1', 'value1');
params.append('para2', 'value1');
this.http.post('/api.php', params).subscribe(....)
Now you can get the parameters on the PHP part of your project with $_POST['para1'] and $_POST['para2'].
I like this solution more than getting all the stuff with file_get_contents, as it looks more straight forward for me.
please try I hope it will help you
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class LandingService {
private apiUrl = 'http://localhost:5000/';
list:any;
headers : any;
constructor(private _http: HttpClient){
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
}
getsearchResponse(searchText){
this.list ={"sentences":searchText}
return this._http.post(this.apiUrl+'searchBotsNew',this.list,this.headers)
.map(res =>res.json())
.do(data => console.log(JSON.stringify(data)));
}
}
I found the solution to this.
In PHP, $_POST only accept formdata.
With request header 'Content-Type: application/json' you can receive it with file_get_contents('php://input');
So
$_POST = json_decode(file_get_contents('php://input'));
I'm trying to do is submit the device IMEI to be inserted into the database.
However, the returned JSON output from the database shows the IMEI as null.
Here's what's been implemented:
Requester
class Requester
{
....
func postRequest(_ url: URL, headers : Dictionary<String,String>?, data: Data?, callback : #escaping (_ response: HTTPResponseWithData) -> Void) -> Void
{
let request = Factory.httpRequest(url, method: "POST", headers: headers, data: data)
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {
data, response, error in
print("RESPONSE: \(response)");
})
task.resume()
}
....
}
Factory
class Factory
{
func httpRequest(_ url: URL, method: String, headers: Dictionary<String, String>?, data: Data?) -> URLRequest
{
var request = URLRequest(url: url)
request.httpMethod = method
if headers != nil
{
for (field, value) in headers!
{
request.addValue(value, forHTTPHeaderField: field)
}
}
if data != nil
{
request.httpBody = data
}
return request
}
}
MainVC
let requester = Requester()
#IBAction func sendRequest(_ sender: Any)
{
var json: Dictionary<String, Any> = [:]
json["imei"] = myIMEI
do
{
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
post(theData: data)
}
catch let error as NSError
{
print(error.localizedDescription)
}
}
func post(theData: Data) -> Void
{
self.requester.postRequest("www.url.com", headers: nil, data: theData, callback: {(response: HTTPResponseWithData) -> Void in
if response.statusCode == 200 && response.data != nil && HTTPHeader.isContentTypeJSON(response.mimeType)
{
print(response.data!)
do
{
if let test = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions()) as? Dictionary<String, Any>
{
print("test = \(test)")
}
}
catch
{
print("ERROR parsing data")
}
}
else
{
}
});
}
What I get back from the output is:
test = ["imei": <null>]
I've looked at numerous questions and answers on SO regarding this, and besides my implementation being in different classes, I don't see what could possibly be wrong.
Here's some snippet of the PHP code:
header("Content-Type: application/json");
$imei = $_POST["imei"];
$something_else = $_POST["something_else"];
$mysqli = new mysqli($host, $userid, $password, $database);
if ($mysqli->connect_errno)
{
echo json_encode(array("success" => false, "message" => $mysqli->connect_error, "sqlerrno" => $mysqli->connect_errno));
exit();
}
echo json_encode( array('imei'=>$imei) );
What exactly is wrong with my POST request implementation that is not allowing me to submit the IMEI to the database?
If it helps, the RESPONSE output is:
RESPONSE: Optional( { URL:
http://www.url.com } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Type" = "application/json";
Date = "Mon, 02 Jan 2017 08:07:54 GMT";
"Keep-Alive" = "timeout=2, max=96";
Server = Apache;
"Transfer-Encoding" = Identity; } })
UPDATE: After further testing, I replaced the above php code after the header with the following code, and now the imei is reported:
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle))
{
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
$request_data = json_decode($raw_post_data, true);
$imei = $request_data["imei"];
I'm confused, why is it the case that the updated php code works but the one involving $_POST does not?
See the $_POST documentation which says it is:
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
But you're not doing x-www-form-urlencoded request. You're performing an application/json request. So you can't use $_POST. Use php://input (e.g., as discussed here: iOS Send JSON data in POST request using NSJSONSerialization).