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?
Related
I have a very "strange" error.
I'm adding an interceptor in my axios and adding a new "header", below an example..
axiosInstance.interceptors.request.use(function (config) {
config.headers['X-Panel-Host'] = document.location.hostname;
return config;
});
After I added this new header, I started having the "CORS ERROR" problem, and so far I wasn't having it, however, I added mine in the backend (PHP) with the authorization as below.
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-Panel-Host, X-Host");
However, I still get a return in the CORS api, if I remove the line that contains "X-PANEL-HOST" the api works again, what did I forget to do?
I know similar questions have been asked, but nothing on here as worked. Thank you in advance!
I'm using fetch from a react JavaScript app (located at http://localhost:3000) to post data too, and get a response from a local PHP API (using XAMPP and located at http://local.api.mysite.com/user)
Every-time I get a 200 status without any returned headers or body. If I go to the PHP URL in my browser it works just fine
I've ensured cors is set in both js and php, set content types, turned off caching, and tried every suggested fix on here and Google.
This is a last resort
JS:
fetch('http://local.api.mysite.com/user', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
},
body: JSON.stringify(data),
}).then(console.log(response))
PHP:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header("Cache-Control: no-cache");
}
// 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);
}
$output = json_encode(['status' => 'recieved']);
header('Content-Length: '.strlen($output));
header('Content-Type: application/json');
echo $output;
exit;
Previously I had limited my PHP headers to be more restrictive, but I found this code block and am using it to let anything pass for testing.
Solution
Rikin's comment on his answer had me open dev tools, go to the network tab, and view the response directly. This showed a server error that was occurring and leading to the empty response with a 200 status
This is fetch issue on how its built. You get a stream of response which you have to either parse it as json or text or blob and then look for actual response that we expect. I modified code a bit below to get you what you need.
fetch('http://local.api.mysite.com/user', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
},
body: JSON.stringify(data),
})
.then(data => data.ok && data.json())
.then(response => console.log(response));
This is what you get back in fetch response: https://developer.mozilla.org/en-US/docs/Web/API/Response
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
So I've been trying to pass data from my front-end to my back-end (however, I'm not very experienced within this area). The data comes through, however, if I try to insert the data into my MySQL-DB through PDO the browser gives me the following error:
Failed to load http://localhost:8888/post_recipe.php: 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:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
JS
postToAPI = () => {
fetch(`http://localhost:8888/post_recipe.php`, {
method: 'POST',
headers: {
'Content-Type': 'text/html'
},
mode: 'cors',
body: JSON.stringify({
title: this.state.title,
description: this.state.description,
userID: this.props.userInfo.response.id,
name: this.props.userInfo.response.name,
stepByStep: (this.state.stepByStep),
recipeIngredients: (this.state.recipeIngredients),
profileImg: this.props.userInfo.response.picture.data.url
})
})
.then((response) => response.json())
.then((fetch) => {
console.log(fetch)
});
}
PHP
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header("Content-type: text/html; charset=utf-8");
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$post = json_decode(file_get_contents('php://input'));
$array = json_decode(json_encode($post), True);
$pdo = new PDO(
"mysql:host=localhost:8889;dbname=veganify;charset=utf8",
"root",
"root"
);
$statement = $pdo->prepare(
"INSERT INTO posts (title, description, userID, name, stepByStep, recipeIngredients, profileImg)
VALUES (:title, :description, :userID, :name, :stepByStep, :recipeIngredients, :profileImg)"
);
$statement->execute(array(
":title" => $array["title"],
":description" => $array["description"],
":userID" => $array["userID"],
":name" => $array["name"],
":stepByStep" => $array["stepByStep"],
":recipeIngredients" => $array["recipeIngredients"],
":profileImg" => $array["profileImg"]
));
}
echo json_encode($array);
?>
So if I delete the MySQL-insertion, the data comes back to the front-end. I have been stuck here for a while now searching various forums for a solution. The error message says that the header is not present, however it is there, as you can see.
Any help would be much appreciated!
Cheers!
Good afternoon, this is because of the apache blocking requests from different sources ie if your backend is at http://yourdomain.com/client and your font-end is at localhost:3001 will cause a because they are of different (host) origins.
To solve:
Use the .htaccess file in your api / backend folder, for example, in my application my index.php is not in localhost / my-api / public directory then my .htaccess file in this directory directory localhost / my-api / public
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Origin: "*" (allow access from any origin)
Header set Access-Control-Allow-Origin: "http://motech-ui.example" (allow access from only "http://motech-ui.example" origin)
Access-Control-Allow-Origin: "http://motech-ui.example | http://other.domain" (allow access from two mentioned origins)
</IfModule>
Or config in apache.conf
Access-Control-Allow-Origin: "*" (allow access from any origin)
Access-Control-Allow-Origin: "http://motech-ui.example" (allow access from only "http://motech-ui.example" origin)
Access-Control-Allow-Origin: "http://motech-ui.example | http://other.domain" (allow access from two mentioned origins)
CORS in Javascript and PHP works like.
OPTIONS method request will be triggered from browser side.
Server side (PHP) should accept the OPTIONS request, by responding 'OK'.
Now a proper POST request will be triggered from browser side, which will go to your functionality location where your PHP code will gets executed.
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
//location where you can handle your request and respond ok
echo 'OK';
}
If you can not control the sever side, you can work around like me on
Client side only.
If you can control server side, you can use server side solution. I am not discus it here.
Only on client side, work around is
use dataType: 'jsonp',
async function get_ajax_data(){
var _reprojected_lat_lng = await $.ajax({
type: 'GET',
dataType: 'jsonp',
data: {},
url: _reprojection_url,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
console.log(data);
// note: data is already json type, you just specify dataType: jsonp
return data;
}
});
} // function
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