RESTful api - cross domain put request issue - php

I'm a long time overflower and eventually signed up.
I've gone through tons of threads but none could help me with my problem.
I am about to create a RESTful API with the slim framework in php and have problems with the crossdomain put requests.
Let me give you a quick introduction to what I've done.
After wrtining the first GET requests I was looking for a method to test my API easily and found the "RESTClient" Firefox addon, it worked well so I continued using it.
After a few tests I tested a self-written code on another server and there the problem occured.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at %1$S. (Reason: CORS preflight channel did not succeed).
What I wonder the most about is the fact that the Firefox addon had no problem to make the request at any time, it always showed the expected response. The error above just occured when I tried to send a request by my own code. I read a lot about cross-origin requests but nothing helped me, I hope you can.
Now first of all let me show you my slim framework php code
<?php
header('access-control-allow-origin: *');
header('Content-Type: application/json');
function output($arr){
echo json_encode($arr);
exit;
}
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->put(
'/put',
function () {
$output = array("status"=>"200","message"=>"This is a put test");
output($output);
}
);
$app->run();
?>
And my test.html
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script type="text/javascript">
(function($) {
var url = 'URL';
$.ajax({
type: 'put',
url: url,
async: false,
crossDomain:true,
dataType: 'json',
success: function(json) {
console.log(json);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
</script>
</body>
</html>
Can someone please explain to me how I can get this PUT request working. I am really in this despair mood right now. I understand all that cross-domain topic but why is he not letting it go after i set the access-control-allow-origin in the php code ? What is the firefox addon doing different? ...

It seems that you forget to add methods in the header.1
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');

Related

How to bypass Cross-Origin Request Blocked CORS request did not succeed in this script?

On my local machine all Ajax requests work just fine and the app works perfectly. It is a different story on the host machine. When trying to execute below Ajax script I get :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://googleads.g.doubleclick.net/pagead/id.
(Reason: CORS request did not succeed).
I spent all day trying to fix this error to no avail. I even added this in the head of every page
<?php ob_start();
header('Content-Type: text/html; charset=utf-8');
header("Access-Control-Allow-Origin: *");
?>
I read about JSONP and I'm wondering how to implement this solution?
This is the short version of the Ajax
$( ".submit-signup-form" ).click(function(e) {
e.preventDefault();
if(formvalues!==''){
$("#sign-up-form-2").submit(
$.ajax({
type: "POST",
url: 'queries/register.php',
data: formvalues,
success: function(customerarr){ //callback}
})
})
});
}
When debugging the app in the console I tried console.log(formvalues) and everything printed out okay. The form does get ALL the variables so I'm not understanding how to make the script work on live host.
You can use this in ajax request...
dataType: 'jsonp', //use jsonp data type in order to perform cross domain ajax
crossDomain: true,

ReactJS POST Parameters Not Sent

I'm simply trying to get POST parameters on my PHP server, sent from my ReactJS app. In the server response, I can see that 'myParameter' is null. I think this is because of the Cross Origin issue, but I've tried many suggestions from answers to similar questions and nothing I've tried has worked. I believe that I'm looking for the proper code to add to my PHP file. It's been days now of this issue and I'm hoping someone here can help.
Background information (in case it matters at all). My PHP file is on my server hosted with hostgator. GET requests with URL parameters work perfectly, but POST parameters seem to be blocked. I'm trying to send more data than the URL option allows.
Thank you so much!
ReactJS Code:
axios.post('https://mywebsite.com/endpoint.php', {
myParameter: 'test',
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
PHP Code:
<?php
header("Access-Control-Allow-Origin: *");
echo json_encode($_POST['myParameter']);
?>
I also tried this, but it did not change the result:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Max-Age: 86400');
echo json_encode($_POST['myParameter']);
?>
EDIT:
Based on the answer from the post linked by Aaqib, I was able to successfully get the data on my server!
i usually prefer the axios constructor with properties. its much more clearer then the short hand methods.
axios({
method:'POST',
url:'https://mywebsite.com/endpoint.php',
headers:{},
data:{
myParameter: 'test'
}
}).then((res)=>{})
.catch((err)=>{});
Try this and see if it works.
axios.post('https://mywebsite.com/endpoint.php', {data: {
myParameter: 'test'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

404 error when trying POST to php file in angularjs

I have seen a lot of questions here with the exact same problem, but none of them have a solution that works for me.
I have a NodeJS server setup and in an Angular controller I'm trying to get a contact form working. On form submission I call this function (this is only one of the many variations on a POST request I've tried):
$scope.submit_contact_form = function(){
$http({
method: "post",
url: 'http://' + window.location.host + "/form-u10657.php",
data: $scope.form_data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data) {
$scope.status_message_toggle("Success");
}).error(function(){
$scope.status_message_toggle("Problem sending mail", 'warning');
});
};
But it always returns a 404 not found error. The php file is definitely in the right directory. Going to the url with a GET request works.
What is different in my setup, that I haven't seen in other questions, is that I am using a NodeJS server and ngRouteProvider.
Other answers have said to allow NodeJS to accept POST requests, but it hasn't been necessary to configure NodeJS before, and I would like to avoid it now.
Is there a way to fix it just in Angular? And if not what should I do with NodeJS to get it working?

Creating a restful API using PHP as server and jQuery as client

I'm trying to create a Javascript client API service which calls the API of my site. This will be cross domain and i'm aware of the problems this causes. However, I need the user to send through some user credentials (whether that be their username and password encoded obviously or an API key + secret) so that I can return user specific details.
I initially looked at using the jsonp datatype however this doesnt allow you to set any custom headers so ruled this out.
I've been searching the web for a while and been unable to find a secure way of doing this cross domain, has anyone had any success with this and can give me some advice?
UPDATE:
I've tried this following code as suggested by lu1s, however I get an alert of 'boo' as stated n the error function..
$.ajax({
url: 'http://www.dotsandboxes.co.cc/__tests/cors.php',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: function (xhr) {
xhr.setRequestHeader('securityCode', 'Foo');
xhr.setRequestHeader('passkey', 'Bar');
}
});
Thanks
You can. Try adding the Allow-Access-Control-Origin: * to your HTTP response headers, as well as the correct content-type.
Try with a simple PHP script like this:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: text/json');
echo json_encode(array('success'=>true,'data'=>'foobar'));
?>
Check this site to read more info about cross-origin: http://enable-cors.org/
About the authentication, it's NOT recommended to send usernames or passwords, even if they're encrypted. As you stated, it's better to pass a token in the URL. Best if following standards like http://oauth.net/2/ .

Javascript: Cross-domain JSON request issues

I am trying to request JSON from Google Places API, but I am still getting the cross-domain request error after firstly including:
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Headers: x-requested-with");
?>
The JSON request I am using is standard JQuery:
function load() {
var url = 'https://maps.googleapis.com/maps/api/place/details/json?reference=CnRhAAAARMUGgu2CeASdhvnbS40Y5y5wwMIqXKfL-n90TSsPvtkdYinuMQfA2gZTjFGuQ85AMx8HTV7axABS7XQgFKyzudGd7JgAeY0iFAUsG5Up64R5LviFkKMMAc2yhrZ1lTh9GqcYCOhfk2b7k8RPGAaPxBIQDRhqoKjsWjPJhSb_6u2tIxoUsGJsEjYhdRiKIo6eow2CQFw5W58&sensor=true&key=xxxxxxxxxxxxxx';
$.ajax(url, {
async: true,
success: function(data, textStatus, jqXHR) {
dump(data);
}
});
}
I would use a JSONP query instead, but the Google Places API doesn't support JSONP...how can I solve this? With a proxy server? I am not sure how to go about this or what I'm doing wrong.
The URL you are requesting data from has to grant permission with access control headers. It would defeat the object of the same origin policy is a remote origin could grant permission to itself!
If the API you are using doesn't provide a JSON-P API, and doesn't set access control headers itself, then you need to use a proxy. Either one you run yourself, or a third party one that will convert to JSON-P (such as YQL).

Categories