I am new angular developer, test app is working fine in localhost. but in the server http post, put, delete all not working. server return 403 forbidden error and also blocked my ip if hitting the page frequently.
TypeScript:
addHero(hero: Hero): Observable<Hero>{
const url = `${this.apiUrl}post.php`;
return this.http.post<Hero>(url, hero, httpOptions).pipe(
tap((hero: Hero) => this.log(`Added id ${hero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}
PHP:
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');
$data = json_decode(file_get_contents('php://input'), true);
Thanks for the help.
Use:
$data = $_POST;
instead.
$_POST is an array with the post data.
Related
Facing CORS in angular, when i was trying to make a API call between my localhost to another domain.I am getting 404 issue .
1.Front End : Angualr 7
Front end request part:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods':'POST',
'Access-Control-Allow-Headers': 'Content-Type'
})
}
login(username: string, password: string) {
return this.http.post<any>('http://remote/djaxtesting/enter_uiupgrade/index.php/api/v1/user/validate',
{acc_type: "ADMIN", uemail: "djax_admin#dreamajax.com", upw: "123456"},httpOptions)
.pipe(map(user => {}))
}
Back end coding :
<?php defined('BASEPATH') OR exit('No direct script access allowed');
header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');
public function validate_post()
{
$role = array('ADVERTISER','TRAFFICKER','ADMIN','MANAGER');
if($this->post('acc_type') !='' and in_array($this->post('acc_type'),$role))
{
switch(strtoupper($this->post('acc_type')))
{
case "ADMIN":
$adminObj = $this->do_networks->validate_user($this->post('uemail'),$this->post('upw'),$this->post('acc_type'));
//$this->response($adminObj, 200);
}
}
}
enter image description here
We using php for api. Helping handing needs to solve this issue ?
The problem with the option method. Option request should be a 200 returning an empty response. Then the browser will send the real POST request.
for that replace with the headers in your PHP File in the constructor. It will work.
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
die();
}
This question already has answers here:
PHP Get JSON POST Data
(1 answer)
Reading JSON POST using PHP
(3 answers)
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 4 years ago.
I just created an angular 7 project
I try to send a post with some data, nothing is set in the header part
so on the server side I only get the php script called, nothing in the $_POST array
this code works fine in angular 5, I should see the data in the header log in chrome
createPostOptions() {
let headers = new Headers({
'Content-Type': 'application/json',
});
let options = new RequestOptions({ headers: headers, withCredentials: true });
return options;
}
getParts(): Observable<any>
{
return this.http.post('http://localhost/site/data.php',{command:'getParts'}, this.createPostOptions())
.pipe(map((response: Response) => {
return this.processData(response,this.router);
}));
}
php code:
function cors()
{
header("HTTP/1.1 " . "200" . " " . "OK");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header('Access-Control-Allow-Headers: Accept, Content-Type, Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Allow-Methods, X-Requested-With, X-API-KEY, X-Auth-Token, X-Requested-With, Authorization, Content-Range, Content-Disposition, Origin, Access-Control-Request-Method');
header('Access-Control-Max-Age: 86400');
header('Access-Control-Allow-Origin: '."http://localhost");
header('Access-Control-Allow-Credentials: true');
}
//-----------------------------------
if($_SERVER['REQUEST_METHOD']=="OPTIONS")
{
cors();
}
else
{
...
}
I should see something like this
Any help apreciated
Since you are sending json in the body, but not as post parameters, you need something like
$jsonInput = file_get_contents('php://input');
$obj = json_decode($jsonInput);
$command = $obj->command;
I'm creating an angular application 6 and api rest in php.
when my angular application tries to perform a request the following url: http://localhost/bdevApi/api/index/categoryexame?page=1
the following error is loaded:
Failed to load Response to preflight request doesn't pass access
control check: No 'Access-Control-Allow-Origin' header is present on
the requested resource. Origin 'http://localhost:4200' is therefore
not allowed access.
The angle is in port 4200 and my api is in 80
I visualized some tutorial and added the following header to my api
api/index.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
include("config/config.php");
include("import/Interpreter.php");
include("import/SendJson.php");
include("database/Connection.php");
include("import/AuthToken.php");
$db = Connection::getInstance();
if( $db->getStateConnection() )
{
$arrayHeader = getallheaders();
$token = isset($arrayHeader["token"]) ? $arrayHeader["token"] : "";
// Recupera dados via Json
$strJson = file_get_contents('php://input'); //echo $strJson;
$jsonObject = json_decode($strJson); //var_dump($strJson);
$Interpreter = new Interpreter(
"http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]",
$_SERVER['REQUEST_METHOD'],
$jsonObject
);
if(AuthToken::validateToken($token))
$Interpreter->initializes(true);
else
{
if($token == "")
$Interpreter->initializes(false);
else
{
$S = new SendJson();
$S->Send("200", "1", "Token não autenticado", null);
}
}
$db->closeConnection();
}
?>
How do I get my application to accept these headers and not show this error?
[EDIT]
[]1
new error
Failed to load
http://localhost/bdevApi/api/index/categoriaexame?page=1: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access.
This is happening because of cross origin policy. You can go through this document to get the details knowledge about CORS:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control
You can try this code below:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
I'm trying to call a web service from angular 5 to PHP.
I'm using POST method but I have trouble retrieving data in PHP side.
Send data is shown in payload but it's not retrieved in php side.
Angular service.ts
this.URL = "http://localhost/angular/WEBSERVICE_PHP/test.php";
const headers = new Headers();
headers.append('Content-Type', 'application/json');
let data = 'visitor_id=55';
return this.http
.post(this.URL,JSON.stringify(data),{
headers: headers
})
.map( Response => console.log(Response) );
PHP PAGE
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET");
header('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies
header('content-type: text/plain');
header("content-type: application/x-www-form-urlencoded");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-
Requested-With");
header("Access-Control-Max-Age: 172800");
if(isset($_POST))
{
// $post = 'test data'; // This data get sent
// return $post;
echo $post = $_POST['visitor_id'];
return $post;
}
When "posting" JSON, you won't see $_POST.
Instead do this:
$json = file_get_contents('php://input');
$array = json_decode($json, true);
If it MUST be $_POST, you can assign the $array to $_POST.
The other solution is from the Angular side, instead of sending the JSON string, send a proper post! (I'm not an Angular man, maybe someone can comment and I'll add the code!)
I have created an app for the Registration Form using [Ionic + PHP] and I face the following issue.
CORS Add-on: Activated - It works Fine when I use it in the http://localhost:8100/ionic-lab
CORS Add-on: Deactivated - It does not works Fine when I use it in the http://localhost:8100/ionic-lab and the below mentioned error occurs.
Below I will explain the codes in my Files.
remote-service.ts
constructor(public http: Http) {
this.headers = new Headers()
this.headers.append('Content-Type', 'application/json')
this.headers.append('Content-Type', 'application/x-www-form-urlencoded')
this.headers.append('Access-Control-Allow-Origin', 'http://localhost:8100')
this.headers.append('Access-Control-Allow-Credentials', 'true')
this.headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD')
this.headers.append('Access-Control-Allow-Origin', '*')
this.headers.append('Accept', 'application/json')
this.headers.append('Accept', 'application/x-www-form-urlencoded')
console.log('Hello RemoteServiceProvider Provider');
}
getAllUsers() {
let options = new RequestOptions({ headers: this.headers })
return this.http.get('http://haitutorial.com/HybridApp/listAllUsers.php', options)
.map(res => res.json());
}
getAllUsers() - This function will fetch all the users Registered from the specific URL.
database.php
<?php
include('database.php');
header('Access-Control-Allow-Origin' , '*');
header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
header('Accept','application/json');
header('content-type','application/json');
$query = "SELECT * FROM `users` WHERE `status`='1' AND `delete_status`='0' ORDER BY `user_id` DESC";
$result = mysqli_query($con,$query);
$count = mysqli_num_rows($result);
$resultant_array = array();
if($count>0)
{
while($informations = mysqli_fetch_assoc($result))
{
$resultant_array[] = $informations;
}
print_r(json_encode($resultant_array));
}
else
{
$resultant_array[] = ["success"=> 200, "message"=> "No Data Found", "status_code"=>1 ];
echo $output = json_encode($resultant_array);
}
?>
The Above URL mentioned in the getAllUsers() works in the Browser but when placed inside the Ionic App it shows the below Error.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://haitutorial.com/HybridApp/listAllUsers.php. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
The above Issue is solved when I enable the CORS add-on in the Browser. But when I Disable the CORS add-on in the Browser it shows the Error.
Like wise the Same Error prevails in the Insert Page Also. When I Insert the Data from the APP it redirects to the List Page and the Data are not displayed telling the above said Error.
I have added header() in the PHP File also. But I am unable to trace out the Error. I am in need to Fix this Error without the use of Add-on like stuffs in the browser and needs to run successfully in APP too.
You need to set header at server end not ionic side.
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");