I've made a web application running on domain http://app.mydomain.tld
and I've APIs on https://api.mydomain.tld (APIs are not developed by me).
I'm doing an AJAX HTTPs GET call with jQuery using this method:
$.ajax({
url: "https://api.mydomain.tld/GetSomething/read.php",
method: "GET",
contentType:"application/json; charset=utf-8",
dataType:"json",
async:false,
headers: {"Accept": "application/json; odata=verbose" },
success: function (data) { doSomething(); },
error: function (data) { showError(); }
});
This call is returning an error like NetworkError: failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://api.mydomain.tld/GetSomething/read.php'.
I've added the Access-Control-Allow-Origin extension for Chrome and the call is working fine.
So I've checked response headers. When Chrome extension is NOT enabled I've this response headers:
Access-Control-Allow-Origin: *
When the extension is enabled I've these headers:
Access-Control-Allow-Headers: access-control-allow-methods,access-control-allow-origin
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin: *
So my question, that could have an obvious answer, is: are these headers required to make correct cross domain calls?
If yes, do my APIs need the below additional code?
<?php
header("Access-Control-Allow-Origin","*");
header("Access-Control-Allow-Methods","GET, PUT, POST, DELETE, HEAD, OPTIONS");
header("Access-Control-Allow-Headers","access-control-allow-methods,access-control-allow-origin");
?>
Is correct what I said or am I missing something to make my call working without changing APIs code?
PS: if possibile I would not use JSONP.
Related
So, I'm having a problem retrieving custom headers from ajax call.
This is my ajax call:
$.ajax({
url: 'api.php',
type: 'get',
processData: false,
beforeSend: function(xhr) {
xhr.setRequestHeader('HASH', '5c268592cd4db9c7f6b813bb689005c6');
},
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
And in my api.php, I have this:
<?php
$headers = getallheaders();
print_r(json_encode($headers));
the output:
......
"Access-Control-Request-Headers":"content-type,hash",
....
This returns null:
echo $headers['hash'];
// or this echo $headers['HASH'];
You are making a cross-origin request (you shouldn't be, since your code shows a relative URL, but perhaps there is an HTTP redirect in play somewhere) and adding custom headers.
This means that it is not a simple request, but requires a preflight OPTIONS request.
The output you see is the headers of the OPTIONS request asking permission from the server to send the request with the custom headers.
You need to grant that permission, then the browser will make a second request (which is the one you are expecting).
header("Access-Control-Allow-Origin: http://example.com/");
header("Access-Control-Allow-Headers: HASH, Content-Type");
header("Access-Control-Allow-Methods: GET");
Try this $_SERVER["HTTP_HASH"];
It is about a javascript pixel to follow up who does what in a sales funnel on the web.
I have a javascript script on my customer thrivecart domain (e.g. https://ownspace.thrivecart.com)
I want to make a request to another domain (e.g. https://emails.mycustomer.com) from which the javascript script is from.
Here is the main part of the javacsript code on https://ownspace.thrivecart.com :
$(document).ready(function () {
console.log("loading pixel");
$.ajax({
url: 'https://emails.mycustomer.com/server_side_script.php',
type: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'},
data: {my:ciphered_get_parameters},
success: function (result) {
console.log(result);
}
});
});
Here is what I have server side for the moment : (server_side_script.php)
<?php
header('Content-Type:application/json');
header("Access-Control-Allow-Origin:https://ownspace.thrivecart.com");
header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, Accept");
// Special data treatment
I get this error on the thrivecart page :
Failed to load https://emails.mycustomer.com/server_side_script.php: Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.
However, I read that "
Access-Control-Allow-Headers :
Indicates which headers are supported by the response’s url for the purposes of the CORS protocol."
As the header is on in the PHP code, I don't understand why it does not work.
I even tried to set the X-Requested-With header in the response with NGINX conf file, restarting the server.
But, I think I miss a point.
Appears to be a typo in
header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, Accept");
Try
header("Access-Control-Allow-Headers:Content-Type, Authorization, X-Requested-With, Accept");
I'd like to load a site from a different domain. I've already set headers through php in my header.php file:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: *");
I've searched around for the correct way to do the ajax request with cross domain enabled and ended up with this:
$.ajax(
{
type: 'GET',
url: target,
processData: true,
data: {},
dataType: "json",
success: function (data)
{
$("#toolsarea").attr('src', target);
}
});
but I still get the error "No 'Access-Control-Allow-Origin". Is there still something I'm missing?
Your issue is related to Same origin policy which prevent JavaScript to make an AJAX request for security reasons.
You need to make sure CORS is enabled on your PHP server.
You can do it using:
<?php
header("Access-Control-Allow-Origin: *")
More information on how to enable CORS on your server can be found here:
http://enable-cors.org/server_php.html
You can read more about Same-origin policy on the client here:
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
I try to get JSON data from my own API, from a $.ajax method with jQuery.
I must have a header 'Authorization-api-key' in my request otherwise I'll have a 401 status code.
$.ajax({
type: "GET",
headers: {'Authorization-api-key' : 'key'},
dataType: "json",
crossDomain: true,
url: "http://urlofmyonlineapi.com/api/ressource",
success: function (data) {
alert(data);
}
});
I have read several threads on stackoverflow about CORS and the'XMLHttpRequest cannot load' problem. So, in my API I have added in response these headers (I use Slim Framework):
$app->response->headers->set('Access-Control-Allow-Origin', '*');
$app->response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$app->response->headers->set('Access-Control-Allow-Headers', '*');
$app->response->headers->set('Access-Control-Allow-Credentials', 'true');
The problem
If I put any header in $.ajax with 'headers: {...}' argument, I have two errors in my browser console:
'OPTIONS' error
'XMLHttpRequest cannot load' error
If I remove headers, I haven't error but I have my 401 status code.
If I remove headers AND my API's authentification with the key in request's headers, I get my data.
I have solved the problem: my API didn't accept OPTIONS request.
(Ajax with jQuery need to make an OPTIONS pre-request)
I have some JQuery code that logs a user into the system by connecting to my api, which is on a subdomain - api.foo.com
My JQuery code is:
$.ajax({
type: "POST",
crossDomain: true,
url: "http://api.foo.com",
data: {json:"true",com:"login",username:$('#LoginUsername').val(),password:$('#LoginPassword').val()},
dataType: "json",
success: function(Data) {
console.log("Request sent and data received");
console.log(Data);
}
});
The issue is that in the console, I get the error XMLHttpRequest cannot load http://api.foo.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://foo.com' is therefore not allowed access.
I know for a fact that I have set the 'Access-Control-Allow-Origin' header to * in my php code - header("Access-Control-Allow-Origin: *"); and I have checked in on google chrome (See screenshot below).
I originally opened a question about this issue but realised I had misspelled the header, whereas this time that is not the case.
The screenshot below is of the headers I receive when I connect to api.foo.com directly.