I am trying to send a json to a php script on a server and even though I have included header in php script to have CORS the console throws error
error message
XMLHttpRequest cannot load http://www.awesomegag.0fees.us/updata.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 403.
my code :
php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Content-Type: application/json; charset=UTF-8");
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);
}
echo"hello";
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
?>
My app.js
.controller('datactr', ['$scope','$http','ApiEndpoint',function($scope,$http,ApiEndpoint) {
$scope.submit=function(){
console.log("step1");
$http({
method:'POST',
url:'http://www.awesomegag.0fees.us/updata.php',
data:{
'name':$scope.name
}
}).success(function(data,status,header,config){
console.log("step2");
console.log(data);
})
});
I tried to make it work using proxy method by making path /api and proxyUrl to updata.php address in ionic.project and then replace url in http service to /api. I get a 500 internal server error.
Can anyone help ?
Update: I have moved to a different server where everything works fine.I guess it is some problem with the server but have no idea how to fix it.
Looks like that your server doesn't allow OPTIONS method.
Modern browser do "pre-flight" request for cross origin request to make sure that it is allowed to do so before sending GET/POST request.
Solution: Enable OPTIONS command. Example for Apache http://httpd.apache.org/docs/trunk/mod/mod_allowmethods.html
Related
I'm using vue3 with codeigniter4 .I am getting a CORS issue with fetch When sending a custom header even I set what should be set for CORS in server side method (Without using the framework filters ,Just pure php)
my js code is :
GetMyOrders() {
fetch(this.AppMainData.ApiUrl+'orders/get', {
method: 'GET',
headers:{
'Role': 'some role',
}
}).then(response => response.json())
.then(data => {
console.log(data);
this.MyOrders = data.result;
this.explode;
return;
})
}
And my php code in codeigniter controller (Not resource) is :
public function GetMyOrders(){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Role ,Content-Type,Origin');
header('Access-Control-Allow-Credentials:true');
$db=\Config\Database::connect();
$data['result']=$db->query("Some SQL Query")->getResult();
return json_encode($data);
}
The fetch is successful when not fetching with header , but when i add my custom header the response is blocked by CORS policy as bellow:
"Access to fetch at 'http://localhost/MyApp/public/api/orders/get' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
Any idea please (Without using External Solutions) !!!
It's solved .As the Bros mentioned in replies (A preflight request issue)
Just adding this checking Request Code in (Routes.php) And The problem is solved
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'GET') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers:Role,Origin , Content-Type');
}
exit;
}
Thank U Guys
So, what I'm trying to do is use a Digital Ocean droplet as an api for an application hosted on a different server. Currently, I'm just developing so this server is from my localhost:3000.
On my client side code (JavaScript) I have:
handleSendData = () => {
const request = new XMLHttpRequest()
request.open('POST', 'http://my-droplet-ip/api/create-image')
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
request.setRequestHeader('Access-Control-Allow-Origin', 'http://my-droplet-ip')
request.send(JSON.stringify(data-object))
}
Finally, in my Laravel application (Laravel Framework 5.8.18) I have a route under routes/api.php:
Route::post('/create-image', 'CreateData');
And I have a controller CreateData.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CreateImage extends Controller
{
/**
* Handle the incoming request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function __invoke(Request $request)
{
return response('Hello World', 200)
->header('Content-Type', 'application/json; charset=UTF-8')
->header('Access-Control-Allow-Origin', '*');
}
}
The problem is when I try to run this request, I get a CORS error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://my-droplet-ip/api/create-image. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)
Under the networking tab I get a 404 not found and the Access header is not there in the response.
Any thoughts out there on this issue?
There is a simple solution to this and it is ok for testing on you local machine.
You could just put in index file to allow cors, but I suggest you building middleware for this.
Here is a link it is explained really nice:)
https://medium.com/#petehouston/allow-cors-in-laravel-2b574c51d0c1
You can put also this in index.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Hope it helps :D
I'm trying make some ajax queries from domain A to domain B which is behind HTTP basic auth
Here is my Jquery (1.9.1) ajax call
jQuery.ajax({
method : "POST",
data: s,
withCredentials: true,
headers: {
"Authorization" : "Basic " + btoa('user:pass')
},
url: "http://domainB/script.php",
success: function(data){
console.log(data);
}
});
And script.php
<?php
header('Access-Control-Allow-Origin: http://domainA');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
header('Content-Type: application/json');
/**
* Some stuff here
*/
echo json_encode( $json_response );
For some reason I ignore, I got this error in javascript console
Access to XMLHttpRequest at 'http://domainB/script.php' from origin 'http://domainA' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
I don't understand what the error is, Access-Control-Allow-Origin is set...
I tried many solutions found a little bit everywhere but without success.. May someone have a solution ?
Thanks
I'd like to post data from domain1.com to domain2.com using AJAX, but my request fails.
Here's is my code on domain1.com:
$.ajax({
type: 'POST',
url: 'https://domain2.com/payment/api/server',
crossDomain: true,
data: {
Name: $("#name").val().trim(),
Email: $("#email").val().trim()
},
dataType: 'json',
success: function(data) {
alert('Success');
},
error: function (data) {
alert('POST failed.');
}
});
and here's my server side code on domain2.com:
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://domain1.com/api/': case 'http://domain1.com/api/':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
$name = $_POST['Name'];
echo $name; // Just to check if I receive the value from index.php
You are checking if Origin HTTP header equals to 'http://domain1.com/api/'. However, MDN CORS docs say:
The origin is a URI indicating the server from which the request initiated. It does not include any path information, but only the server name.
You have to remove the path from the string, i.e. it has to be 'http://domain1.com'.
Corrected server.php code:
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://domain1.com':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
$name = $_POST['Name'];
echo $name;
As a side note: if you are using the "HTTP_ORIGIN" header to "secure" your requests, you should rethink it. Anyone can spoof this header and arbitrarily set the value. You are better off using some kind of key/secret to avoid unwanted requests. See: Is CORS a secure way to do cross-domain AJAX requests?
I'm developing a REST-ful application using Yii framework for the server side and Angular JS for the client side
I'm using the restfulyii extension to generate the api
:And I'm facing a problem when I'm sending a PUT request.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ..... This can be fixed by moving the resource to the same domain or enabling CORS.
But it's working for post + get requests
I saw different solutions but none of them worked.
I tried to put those is server side
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: x-requested-with, Content-Type, origin, authorization, accept, client-security-token");
header("Access-Control-Max-Age: 1000");
and tried to put this code in the angular js module:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
and also I tried to put
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
The request converted into OPTIONS request
and the response from the server became as following:
Access-Control-Allow-Headers:x-requested-with, Content-Type, origin, authorization, accept, client-security-token
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS Access-Control-Allow-
Origin:http://localhost:8383
Access-Control-Max-Age:1000
Connection:close
Content-Type:text/html Date:Fri, 24 Oct 2014 06:49:32 GMT
Server:Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.9 X-Powered-By:PHP/5.5.9
I have a base controller for all my rest controllers that use restangular which has the following events.
public function restEvents()
{
$this->onRest('req.cors.access.control.allow.origin', function() {
return ['*']; //List of sites allowed to make CORS requests
});
$this->onRest('req.cors.access.control.allow.methods', function() {
return ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']; //List of allowed http methods (verbs)
});
$this->onRest('req.auth.cors', function ($allowed_origins) {
if (in_array('*', $allowed_origins)) {
return true;
}
if((isset($_SERVER['HTTP_ORIGIN'])) && (( array_search($_SERVER['HTTP_ORIGIN'], $allowed_origins)) !== false )) {
return true;
}
return false;
});
$this->onRest('req.cors.access.control.allow.headers', function($application_id) {
return ["X_{$application_id}_CORS", "Content-Type", "Authorization", "X_REST_REQUEST"];
});
}
Client side I am using restangular with the following options:
RestangularProvider.setDefaultHttpFields({withCredentials: true});
RestangularProvider.setDefaultHeaders({X_REST_CORS: 'Yes'});
RestangularProvider.setDefaultHttpFields({cache: false});
I hope this helps....