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.
Related
I'm using WordPress and from the code i have added a json get request.
This json result is hosted on other server in asp.net platform below is my code :
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('....api/data/Getallunits', function(err, data) {
mydata = data;
});
I'm getting this error:
"Access to XMLHttpRequest at '...../api/data/Getallunits' from origin 'mywordpress' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
Is there anything can be done by adding in wordpress, any phpcode or any plugin
i tried with WP-CORS plugin but didn't worked, please advice if any code should be added on the json get request or any other edits.
I am trying to subscribe to a firebase cloud messaging topic with the following http post request:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://iid.googleapis.com/iid/v1/etLaB36oW1w...nyO_Zc26ZPOFTeNuf58-l6uSoJ9Xs1JRYKfqxsmKkdrR-oX4tQsuS_z5C0/rel/topics/Byfjordskole");
xhr.setRequestHeader("authorization", "key=AAAABlxTfxY:APA91bGE3sa09zq...dZSIVJul3N-y1hMJqAoKngwjC_El3rEuH4_-S2gOxKcdAF67HHhGK7pAWJrhyt8JthJGm_QN6JdXTBow62nYodgFvLncfSniwtBinBgIPLaKpT");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "a3ce72a5-f8ba-99e4-59d6-fe3295b84f6e");
xhr.send(data);
This works when I use Postman, but I get the following error message when I try to use the same code on my javascript app:
XMLHttpRequest cannot load https://iid.googleapis.com/iid/v1/eOEiRqvhD4s:APA91bFFb-uP-Xhf2iD-ALUI_X4M7…gA_YgQgmuib7cCL7UuSdlhUUWmsqwRnkcO2kpAIV_H-_xBPlPd/rel/topics/Eiganesskole.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://sk......e.top' is therefore not allowed access.
Do firebase cloud messaging inhibit me from making this types of request, or is there a solution to this problem? Any help will be highly appreciated.
This Stack Overflow answer solved my problem: https://stackoverflow.com/a/2067584/6177181
The problem was browser security related: and this kept me from making cross domain requests. The Solution was to wrap my code in script tags to avoid this restriction. So instead of doing this request from another javascript file, I simply added the request code in the index.html file like this:
<script>
function subscribe(currentToken){
"use strict"
let stored_topics = localStorage.getItem("topicsList");
let topics = JSON.parse(stored_topics);
for (let i = 0; i < topics.length; i++){
let data = null;
let xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
let body = {};
let url = "https://iid.googleapis.com/iid/v1/"+currentToken+"/rel/topics/"+topics[i];
xhr.open("POST", url);
xhr.setRequestHeader("authorization", "key=AAAABlxTfxY:....QAVfBJI8J0RdZSIVJul3N-y1hMJqAoKngwjC_El3rEuH4_-S2gOxKcdAF67HHhGK....2nYodgFvLncfSniwtBinBgIPLaKpT");
xhr.setRequestHeader("content-type", "application/json");
xhr.send(data);
}
}
</script>
(The currentToken is requested from the firebase cloud messaging API in the same file(index.html)).
Follow the instructions on this link :https://firebase.google.com/docs/cloud-messaging/js/receive for information about Firebase cloud messaging.
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 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.
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.