I have followed a tutorial (and read many others) on making cross-domain requests, but I can't get it to work. I keep getting the same error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is the code I'm working with. I'm trying to hit the coinbase API.
// 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;
}
// Make the actual CORS request.
function makeCorsRequest() { // All HTML5 Rocks properties support CORS.
var url = 'https://www.coinbase.com/api/v1/prices/historical';
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();
}
makeCorsRequest();
By default, you're not allowed to make cross-domain AJAX calls. If the target defines a CORS policy, then this rule may be relaxed. Details.
If you control the target, you should be able to get this to work by adding a CORS policy.
Related
I've read a few StackOverflow posts, googled it but still can't get what I want.
I simply want to get a JSON from Google's API and import it to a variable so I can filter it the way I want, the following code is what I have so far:
<!DOCTYPE html>
<html>
<body>
Term: <input type="text" id="field1" value="Mc Donalds in New York"><br>
<button onclick="myFunction()">Search</button>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
xhr.responseType = 'json';
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
xhr.responseType = 'json';
} else {
xhr = null;
}
return xhr;
}
function myFunction() {
var termo = document.getElementById("field1").value;
var URL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query="+termo.replace(" ","+")+"&key=HIDDEN_KEY";
var data = createCORSRequest('GET',URL);
if (!data) {
throw new Error('CORS not supported');
}
}
</script>
</body>
</html>
When I do:
console.log(data);
I get:
When I do:
JSON.parse(data.responseText);
I get:
Uncaught DOMException: Failed to read the 'responseText' property from
'XMLHttpRequest': The value is only accessible if the object's
'responseType' is '' or 'text' (was 'json').
What should I get on console.log:
https://pastebin.com/4H7MAMcM
How can I get the JSON from XMLHttpRequest correctly?
Also worth mentioning, I'm using Cross-Origin Resource Sharing (CORS) because I couldn't access the domain from my local IP.
--Edit--
Phil thought this was a matter of not being able to return response from a asynchronous, but its wrong, I've tried using Ajax, XMLHttpRequest and now using CORS, the duplicate notation was incorrect, please remove it.
This behaviour is documented on MDN;
If responseType is set to anything other than the empty string or "text", accessing responseText will throw InvalidStateError exception.
Instead, you need to use the response property. Since you specified json as the responseType, response will be a JavaScript object (no need to JSON.parse it).
Aside from this, you'll also need to treat the AJAX request as asynchronous, rather than synchronous. For more info on that, see How do I return the response from an asynchronous call?.
Eventually, you should end up with something like;
function createCORSRequest(method, url, cb) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
cb(this.response);
}
}
xhr.send(null);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
xhr.responseType = 'json';
} else {
xhr = null;
}
return xhr;
}
createCORSRequest('POST', '/echo/json/', function (response) {
console.log(response);
});
https://jsfiddle.net/ez3xt6ys/
However, the browser support seems patchy for this at best; https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response. Instead, it is more common to see the responseType being left as text, and for people to JSON.parse() the responseText property.
I'm having a problem related to cors, I can't get rid of famous
XMLHttpRequest cannot load external domain.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'mydomain.com' is therefore not allowed access
What I tried:
http://www.html5rocks.com/en/tutorials/cors/ - End-to-End Example , still doesnt work , getting the same error.
https://www.sencha.com/forum/showthread.php?299915-How-to-make-an-ajax-request-cross-origin-CORS
other various examples
// 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('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://updates.html5rocks.com';
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();
}
Example above only works in launching static html when I upload it to main domain I'm getting error which I mentioned above.
I just found how to do it with http://cors.io/ .
http://cors.io/?u=http:(your url without brackets)
WORKS LIKE A CHARM.
THANK YOU TO EVERYONE WHO CONTRIBUTED.
Make sure on your server Access-control-allow-origin is set to *
Assuming lets say its nodejs
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
I am successfully sending a XMLHttpRequest by using:
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 = 'http://www.whatismyip.com';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
};
xhr.onerror = function() {
// Error code goes here.
};
xhr.setRequestHeader('referer', 'http://www.google.com');
xhr.send();
However, I could not able to define my referer. What is the correct way to add the custom referer?
You cannot. The XMLHttpRequest specification forbids the altering of the referer header (this stops sites lying in it to bypass security checks which some sites use the referer for).
Terminate these steps if header is a case-insensitive match for one of the following headers:
…
Referer
…
You can try something like this:
xhr.setRequestHeader('X-Referer', window.location.href);
And then read this custom X-Referer header.
Answer found on https://www.trustedsec.com/blog/setting-the-referer-header-using-javascript/
You can set it using window.history.replaceState(null, '', 'https://yourwebsite.com/forged/referer')
As far as I know it only works with the same domain, but you can forge the path this way.
See https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
I wrote the following JavaScript to call a Smartsheet API:
$.get( "https://api.smartsheet.com/1.1/users/sheets", "Authorization: Bearer [My Access token]" )
.done(function( data ) {
alert( "Data Loaded: " + data );
});
But this threw the following error:
XMLHttpRequest cannot load https://api.smartsheet.com/1.1/users/sheets?Authorization:%20Bearer%[My Access token]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
After some reading, I realized the code had to make a cross-origin resource sharing (CORS) request. I came upon the following code to do that using jQuery from here:
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;
}
alert("cors created");
return xhr;
}
var xhr = createCORSRequest('GET', "https://api.smartsheet.com/1.1/users/sheets?Authorization=Bearer+[My Access token]");
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.onload = function() {
var text = xhr.responseText;
alert('Response from CORS request: ' + text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
However, this again produces the same error in my browser console:
XMLHttpRequest cannot load https://api.smartsheet.com/1.1/users/sheets?Authorization=Bearer+[My Access token]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Am I headed in the right direction? How can I fix the issue?
Thanks.
As has been alluded to in the comments, the Smartsheet API does not currently support CORS.
Via javascript (jQuery) I'm trying to load the contents of some pages from Google Sites onto elements in pages in a different site. Using jQuery's load I get the expectable:
XMLHttpRequest cannot load https://sites.google.com/site/foo/home. No 'Access-Control-
Allow-Origin' header is present on the requested resource. Origin 'http://bar' is
therefore not allowed access.
I tried with CORS, using the code below (which I found at http://www.html5rocks.com/en/tutorials/cors/), but got the same result.
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;
}
function makeCorsRequest() {
var url = 'https://sites.google.com/site/edumonkihelp/test0';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onload = function() {return xhr.responseText;};
xhr.onerror = function() {alert('Woops, there was an error making the request.');};
xhr.send();
}
So I guess I have two questions:
1. Can you access the contents of pages in Google Sites?
2. Are there any other similar services out there that would allow you to do so?
Thanks!
According to Google Sites Data API you can use the path parameter to fetch that particular page located at http://sites.google.com/site/siteName/path/to/the/page:
GET /feeds/content/domainName/siteName?path=/path/to/the/page
In order to perform Ccoss-domain requests using jQuery.ajax() specify dataType: 'jsonp'
Example
The example demonstrates how to retrieve page located at https://sites.google.com/site/nokiaofficescontacts/hq:
$.ajax({
url: 'https://sites.google.com/feeds/content/site/nokiaofficescontacts?path=/hq&alt=json',
success: function (data) {
console.log('Page was succesfully retrieved');
console.log(data.feed.entry[0].title); //print Page Title
},
error: function (error) {
console.log(JSON.stringify(error));
},
dataType: 'jsonp'
});
Note: alt=json is specified to request a response in JSON format.