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
Related
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.
I need to know how to pass parameters between angular 7 and a PHP API
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getUsers() {
return this.http.get('http://localhost/backend/json/data_products.php');
}
getProduct(productId) {
const params = new HttpParams().set('id', productId);
return this.http.get('http://localhost/backend/json/data_product.php/', {params});
}
}
but I got this error
core.js:12584 ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK
Please refer to Angular doc: https://angular.io/api/common/http/HttpClient#get
get(url: string, options: { headers?: HttpHeaders | { [header:
string]: string | string[]; }; observe?: "body"; params?: Ht...)
It should be like:
this.http.get('http://localhost/backend/json/data_product.php/', { params: params });
in your case.
I think you need to pass header in request like below.May be this is help you.
update(id: number, data: any){
let model = JSON.stringify(data);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.put( 'http://localhost/backend/json/data_product.php/'+id,model, options);
}
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'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
I have imported following module
import 'rxjs/add/operator/toPromise';
import {Http,Headers,RequestOptions} from '#angular/http';
and i have set in headers are
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
and make call like this
this.apiUrl ="some api url here";
return this.http.get(this.apiUrl+'user-details.php?e='+email+'&p='+password,{headers: headers})
.map(res => res.json())
.toPromise()
.catch(this.handleError);
it's working good on browser and returns result
But when i run on device it shows error as "response with status: 0 for url: null".
please guide me to fix this issue