I create safari extension and i inject js in this extension. In this JS code i send ajax call which create following error in console. "Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers"
here is my code:
this function i copied from net to solve cross domain issue but its not working please help me to figure out this.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR has 'withCredentials' property only if it supports CORS
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") { // if IE use XDR
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("get", "https://www.karmora.com/list.xml");
if (request) {
// Define a callback function
request.onload = function () {
};
// Send request
request.send();
}
$.get('https://example.com', function (data) {
alert("Ajax call successfull");
});
Your problem is related with Same-origin_policy
If you have access to the server, add to Apache Web Server virtual host configuration the following settings:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
Related
I currently have a script that makes an ajax request using XMLHttpRequest(). The essence of the script is to keep track of certain analytics and here's how it was implemented.
Adds an event listener and sends data to start_tracking_analytics script
document.addEventListener('DOMContentLoaded', function(){
try{
//url to send data to
var url = 'https://subdomain.domain.com/start_tracking_analytics.php?key='+tracker_key;
//host name
var host = location.protocol + '//' + location.hostname
//send data
sendAnalytics(url, host);
setTimeout(function(){
setInterval(function(){
try{
sendUpdateAnalytics();
}catch(e){
}
}, 7500);
}, 1000);
}catch(e){
}
});
Here's how the sendAnalytics function is implemented
function sendAnalytics(url, host){
try{
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var method = 'POST';
var xhr = createCORSRequest(method, url);
xhr.onerror = function() {
// Error code goes here.
};
xhr.send();
}catch(e){
//...
}
}
Here's how sendUpdateAnalytics was implemented. Note: This gets triggered at intervals
function sendUpdateAnalytics(){
try{
//url to send data to
var url = 'https://subdomain.domain.com/end_tracking_analytics.php?id='+tracker_session_id;
//current host
var host = location.protocol + '//' + location.hostname
//send the data
sendData(url, host);
}catch(e){
}
}
Now, to the backend (response) script. i.e - start_tracking_analytics.php && end_tracking_analytics.php
On both scripts, I had this headers set
//GET variables
$host = $_GET["host"];
$key = $_GET["key"];
//set header for CORS
header("Access-Control-Allow-Origin: $host");
header("Access-Control-Allow-Credentials: true");
//I Do all of my computations here and echo an integer
echo 1;
The problem: 1 out of 10 requests made to end_tracking_analytics returns CORS error
Access to XMLHttpRequest at 'https://subdomain.domain.com/end_tracking_analytics.php?id=1&host=https://www.hostUrl.com&key=XXXXX' from origin 'https://www.hostUrl.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I really do hope this is explanatory and will be happy to provide more details if it's not. Any idea why this could be happening?
I'm so desperate because I can't see the light in this endless darkness, the problem is, that there is no way to stop "pre-flight" options response from appearing and of course can't reach certain API, I've been looking and reading stuff about CORS but without luck.
This is the function in the API that should display an array:
function main_get() {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: SOME-KEY');
header('Access-Control-Max-Age: 1728000');
header("Content-Length: 0");
header("Content-Type: text/plain");
$array['results'] = array(
array(
"adId"=>"8847575",
"make"=>"SOMEMAKE",
"model"=>"Some model",
"year"=>"2008",
"version"=>"The version",
)
);
$this->response($array, 200);
}
I'm using Codeigniter and REST plugin for the API.
Note that the headers are included
This is the code for the request sample:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function makeCorsRequest() {
var url = 'http://*****/api/test';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader('SOME-KEY', 'dffs54f78v');
if (!xhr) {
document.getElementById("response").innerHTML = 'CORS not supported';
return;
}
xhr.onload = function () {
var text = xhr.responseText;
document.getElementById("response").innerHTML = text;
};
xhr.onerror = function () {
document.getElementById("response").innerHTML = 'Woops, there was an error making the request.';
};
xhr.send();
}
makeCorsRequest();
Got this code from some CORS tutorial in the internet.
And still can't get rid of this:
main.js:40 OPTIONS http://*****/api/test 404 (Not Found)
makeCorsRequest # main.js:40 (anonymous) # main.js:43 localhost/:1
Failed to load http://*****/api/test: Response for preflight has
invalid HTTP status code 404.
What am I doing wrong?
I know there may be an answer somewhere, but I've wasted 3 days at this thing and found nothing.
Thanks in advance
In my Javascript file I want to load xml data from this site: https://www.anime2you.de/feed/
But I always get a no Access-Control-Allow-Origin header despite using CORS. Did I misunderstand the concept / usage of CORS or is the website faulty?
My code:
var feeds = ["https://www.anime2you.de/feed/"];
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'https://www.anime2you.de/feed/';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
alert("success");
};
xhr.onerror = function() {
alert("fail");
};
xhr.send();
Thanks in advance
Nova
Have you set the header("Access-Control-Allow-Origin: *"); on the script you are requesting? https://www.anime2you.de/feed/ if you are using Access-Control-Allow-Origin with a wildcard then set the credentials to false in
xhr.withCredentials = false;
If you can set the domain name of the server making the request i.e
header("Access-Control-Allow-Origin: http://domain-where-js-sits");
then you can do:
xhr.withCredentials = true;
and set these other headers:
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type
An alternative is to use jsonp - this may not work for you as the response needs to be in json:
function response(data) {
edit the returned data here
}
var script = document.createElement('script');
script.src = 'https://www.anime2you.de/feed/?callback-response';
document.body.appendChild(script);
I am working on getting a data through a URL with GET method available.
I have used the Jquery to get the JSON and parse it into HTML table.
However, I cannot fix the CORS issue. I have added the code:
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', 'True');
res.header('Access-Control-Allow-Headers', 'accept, content-type, x-parse-application-id, x-parse-rest-api-key, x-parse-session-token');
I have also installed the chrome extension to enable CORS.
However, none of them worked. I have also tried to use XMLHttpRequest directly, it still doesn't work...
Here is my code using Jquery:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var url = 'https://www.probancemail.com/rest/v2/stats/RT1-PREM_DE?&token=5eX8dIljx9fWOvFu7WO22uL3EEYSN8PEciwZKdYqKxK6HOsHxjyYQpVBQiSLEGOJkId9wTNOAUpGRPfPWJgXV5u8s9EUL9hVeGSa'
function FIXCORS(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', 'True');
res.header('Access-Control-Allow-Headers', 'accept, content-type, x-parse-application-id, x-parse-rest-api-key, x-parse-session-token');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
$(document).ready(function () {
$.getJSON(url,
function (json) {
tr = $("<tr></tr>")
for (var i = 0; i < json.results.length; i++) {
var td = "<td>" + json.results[i].address_components[0].long_name+"</td>"
$(tr).append(td);
}
$('table').append($(tr));
});
});
</script>
</head>
<body>
<table></table>
</body>
</html>
It always shows the error message of No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
And is my code using HTTP Request directly, which is based on this article: https://www.html5rocks.com/en/tutorials/cors/
<!DOCTYPE html>
<html><meta charset="utf-8"/>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function reqListener() {
console.log(this.responseText);
}
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('/campaign');
}
// Make the actual CORS request.
function makeCorsRequest() {
// This is a sample server that supports CORS.
var url = 'https://www.probancemail.com/rest/v2/stats/RT1-PREM_DE?&token=5eX8dIljx9fWOvFu7WO22uL3EEYSN8PEciwZKdYqKxK6HOsHxjyYQpVBQiSLEGOJkId9wTNOAUpGRPfPWJgXV5u8s9EUL9hVeGSa';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
</script>
</head>
<body>
<div id = "div"></div>
<button type = "button" onclick = "makeCorsRequest">Retrieve Report Data</button>
</body>
</html>
This one doesn't have error message but has no outcome at all...
Is there anyone have some thoughts?
Any feedback is welcomed!!!
Thanks a lot in advance!
CORS should be supported on the server. In case of sending cross-domain request, jQuery adds Origin: http://example.com header to request and expects Access-Control-Allow-Origin: http://example.com or Access-Control-Allow-Origin: * header in response.
You can read more about CORS at MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
P.S. Regarding FIXCORS function in your script, I assume you have copied that from some Node.js CORS guide, it should be place on the server as well
Hi everyone i'am fighting and searching solutions about this from 3 days. I have a problem getting data from sharethis.com RESTapi. I am working with jQuery and Laravel 5.2. I want to get values from this json: http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com but i'am very frustated trying a lot of methods and functions. My actual code is this:
function setHeader(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
}
$.ajax({
url: 'http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com',
type: 'GET',
beforeSend: setHeader,
contentType: 'application/json; charset=utf-8',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});
This request always return "Failed!". I understand a little what CORS means but on practice i can't make it work. Any ideas? Thanks..
Maybe you actually don't understand CORS :)
These headers have to be present in the response, not in the request.
The server has to provide them.
The server has to agree.
The URL you provided doesn't have CORS headers so you can't fetch it via AJAX unless you modify the backend.
Run this code with XMLHttpRequest to get data
var url = "http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com";
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader(
'X-Custom-Header', 'value');
xhr.withCredentials = true;
xhr.onload = function () {
if (this.status === 200) {
console.log(xhr);
}
};
xhr.send();
And there is the function to check if the url support CORS
function createCORSRequest(method, url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
console.log("for chrome/fir");
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
console.log("ie");
} else {
// CORS not supported.
xhr = null;
console.log("not supported");
}
return xhr;
}
hope it helps, regards