CORS no Acess-Control-Allow-Origin header - javascript

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);

Related

Why does 1 out of 10 of my requests returns CORS error in the browser

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?

Javascript CORS "pre-flight"

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

JS - open PDF in new Tab via XHR - with filename and auth header

Thank you for reading!
I want to open a PDF from a REST backend that gets loaded via XHR in a new tab with specified filename and Authorization header.
So far I managed to download it with this (incl. auth headers and filename):
// saves XHR stream as file with configurable filename
downloadXHRFile:function(endpoint,data,method,filename,errorcallback,mimetype){
bsLoadingOverlayService.start();
var def = $q.defer();
var token = localStorageService.get('token');
var xhr = new XMLHttpRequest();
xhr.open(method, CONFIG.URL+endpoint, true);
xhr.setRequestHeader('Authorization', 'Bearer '+token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob=new Blob([this.response], {type:mimetype});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=filename;
link.click();
bsLoadingOverlayService.stop();
}else{
bsLoadingOverlayService.stop();
errorcallback(xhr.statusText);
}
def.resolve();
};
xhr.send(
JSON.stringify(data)
);
return def;
},
Further I managed to open it in a new tab with the following code (incl. auth headers).
Unfortunately the URL (and by that the filename) looks like this:
blob:http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651
Probably it can be solved somehow like above but I cant find the solution.
Does someone have a clever idea how I could set the filename in the new Tab?
// opens XHR filestream in tab
openXHRFile: function(endpoint,filename,errorcallback){
var token = localStorageService.get('token');
var our_url = CONFIG.URL+endpoint;
var win = window.open('_blank');
downloadFile(our_url, function(blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", 'Bearer '+token);
// xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}else{
}
};
xhr.send(null);
}
},

Ajax Jquery CORS not working

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

Need Help to solve ajax issue?

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"

Categories

Resources