Failed to load https:// ... : No 'Access-Control-Allow-Origin' header [duplicate] - javascript

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 4 years ago.
Hi Maybe you can help enlighten me :)
Im trying to make a simple Quote Generator app in pure Javascript (no jQuery), and Im trying to load the following api
https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en
but I keep getting the following error, whether on local host or if I upload it to a host:
Failed to load
https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:50969' is therefore not allowed
access.
The code Im using is the below:
// JavaScript Document
var xhr = new XMLHttpRequest();
xhr.open('GET',"https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en",true);
xhr.responseType = 'text';
xhr.send();
xhr.onload = function() {
if(xhr.status === 200) {
var myStuff = JSON.parse(xhr.responseText);
console.log(myStuff);
}
}
If I use an API url with a .json at the end such as:
http://api.wunderground.com/api/3a9c68e56dd0e1fb/conditions/q/90210.json
it works fine, but if I use anything without the .json it gives me that error.
Ive searched all day and cant find a solution and I really don't want to use jQuery for this.

It's about CORS
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
this should help - actually there is no way you could do it from website. your request will be blocked by your browser. what you can probably do is to write backend proxy that will do it.

quick and easy answer - You are requesting a resource that is only supposed to be requested from the same origin, meaning from https://forismatic.com
It works with JSON because JSON works in a bit different way, but for the normal API call to work, someone on the API server would have to allow your website's origin for it to be able to make secure calls to the server.
You can try using JSONP for the request and see if it helps.

Related

Change CORS policy with javascript alone? [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 2 years ago.
I have an idea have for a webapp to help me improve my front end development. When I'm refactoring front end code I want to be able to quickly visually check through all the instances on my site.
My current plan is to load them within a series of iframes and to be able to flick through instances on each iframe. After discussing it with a friend, the plan we came up with was to use a js script to 1) give iframe/CORS access to the page and 2) scan the page and send instances of the class to the parent (the site with the iframe). I want the site to run separately so it can be a stand alone project. (So I'm running "CSS Friend" on localhost:4000 and the site I'm refactoring on localhost:3000.
The use of a js script would be ideal so that no matter your framework, you could add this script to your application.html file and then it would work.
I am able to give CORS access to iframes through changing my config settings in my development.rb file (as in sever side), but when I run:
<script>
console.log("script working");
var method = "POST";
var url = "http://localhost:4000";
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
var text = {"command":"PUSH"};
xhr.send(text);
</script>
(An idea from this answer: javascript set header Access-Control-Allow-Origin)
I get the following error:
Access to XMLHttpRequest at 'http://localhost:4000/post' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Is it possible to change CORS setting with a JS script, or does it always have to happen on the server side?
You can't change the CORS policy with javascript, because the CORS policy exists to make sure any random website, can't do whatever malicious thing it wants to do. This would all be useless if you could turn it off with javascript.
It exists to protect you against javascript, so it's obvious javascript can't turn it off. It would be a bit like writing your password on a note next to your computer. It'd be a bit pointless.
What you could do however (on the server side), Is attach a "Access-Control-Allow-Origin: *" header to the http response from localhost:4000.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

If CORS if refusing my API request and I don't control the server, is there nothing I can do? [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
So as I understand it, the person who hosts content on their server can set CORS headers which specify who can access this content and what they can do with it. The owner can also prevent certain sites from accessing these items by only allowing specific sites through using the Access-Control-Allow-Origin header.
Is any of that correct, or have I misunderstood how CORS works?
I am trying to access information from a server I do not control and am receiving the CORS error below. I am using the API provided by the owners, but I'm making requests from my localhost dev server and wonder if this might be causing issues? I am developing using Quasar and Vue and I'm very, very new to developing generally - please excuse any obvious mistakes/oversights.
Here's my code:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener('readystatechange', function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open('GET', 'url');
xhr.setRequestHeader('X-Correlation-Id', 'id');
xhr.setRequestHeader('content-type', 'something+json; UTF-8');
xhr.setRequestHeader('authorization', 'Basic username:password');
xhr.send(data);
And I'm receiving this:
Access to XMLHttpRequest at 'url' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I have almost no idea what this means, and I have done a fair bit of reading trying to understand it. If there is an obvious fix, please go the step further to explain it to me - thankyou!
You can always use a CORS proxy like cors-anywhere or you could even make your own.

Access-Control-Allow-Origin Failure ( in some cases) [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
I'm starting to despair.
I run a Wordpress website where I call various rest API interfaces. The problem is that some of my calls are blocked. I have already edited in the various wp files (function.php, http.php, .htaccess, etc.) but without success. The problem persists, but the odd thing is that only certain API calls will be blocked.
These are two example calls:
var httpRequest1 = new XMLHttpRequest();
httpRequest1.open("GET", "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd", false);
httpRequest1.send(null);
var jSONText1 = httpRequest1.responseText;
var httpRequest2 = new XMLHttpRequest();
httpRequest2.open("GET", "https://siamining.com/api/v1/network", false);
httpRequest2.send();
var jSONText2 = httpRequest2.responseText;
The first call works without problems and i get responding Json, but with the second I get the following error message:
Access to XMLHttpRequest at 'https://siamining.com/api/v1/network' from origin 'http://my-website.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
In various files I tried ,
Access-Control-Allow-Origin: *
to insert, but that was synonymous with no success. I do not understand what the difference between the two calls is and why the second one get blocked.
The https://siamining.com/api/v1/network have the Access-Control-Allow-Origin header set to false.
The only way to circumvent it is to make the request server side having your own server that talks with siamining.com and from your wordpress javascript now you call your server endpoint that gives the reponse you want.

Making REST calls to AWS S3 using Pure Javascript (No SDK)

I am trying to make a GET request to AWS S3 using pure Javascript. This is because I am unfortunately no longer able to use the SDK for all of my requests. I have been attempting to follow the documentation provided by Amazon, however I have made very little progress. So far, I have only been able to generate my signature key. I would be enthused if someone could post an example of pure Javascript that makes a simple call to retrieve an object or even lists all of the objects with a specific prefix. I am, to be perfectly honest, completely lost reading their documentation. It seems like it is only useful for people who are intimately familiar with making these calls. #1 and #2 on this image here are what I'm struggling with. I think I sort of understand what they are wanting but I don't know how to fully translate it into an actual request. Unfortunately the code examples on their docs are very few and far between - and a lot of them are just pseudocode/small fractions of the whole thing
edit: Hello is anyone even reading this
edit2: Here's some stuff that isn't working that I'm trying to figure out how to do
var signingKey = getSigningKey(dateStamp, secretKey, regionName, serviceName);
var time = new Date();
//fullURL is something like https://s3.amazon.aws.com/{bucketName}/{imageName}
time = time.toISOString();
time = time.replace(/:/g, '').replace(/-/g,'');
time = time.substring(0,time.indexOf('.'))+"Z";
var request = new XMLHttpRequest();
var canonString = "GET\n"+
encodeURI(fullURL)+"\n"+
encodeURI("Key=asd.jpeg")+"\n"+
"host:s3.amazonaws.com\n"+
"x-amz-content-sha256:"+CryptoJS.SHA256("").toString()+"\n"+
"host;x-amz-content-sha256\n"+
CryptoJS.SHA256("").toString();
var stringToSign = "AWS4-HMAC-SHA256\n"+
time+"\n"+
"20181002/us-east-1/s3/aws4_request\n"+
CryptoJS.SHA256(canonString).toString();
var authString = CryptoJS.HmacSHA256(signingKey, stringToSign).toString();
var queryString = "GET https://s3.amazonaws.com/?Action=GetObject&Version=2010-05-08 HTTP/1.1\n"+
"Authorization: AWS4-HMAC-SHA256 Credential="+accessKey+"/20181002/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature="+authString+"\n"+
"host: s3.amazonaws.com\n"+
"x-amz-date: "+time+"\n";
request.open("GET", "https://s3.amazonaws.com/?Action=GetObject&Version=2010-05-08", false);
request.setRequestHeader("Authorization", "AWS4-HMAC-SHA256 Credential="+accessKey+"/20181002/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature="+authString);
request.setRequestHeader("host", "s3.amazonaws.com");
request.setRequestHeader("x-amz-date", time);
request.send();
edit3: Here are a bunch of errors I get, presumably because I have no idea what I'm doing.
index.js:61 Refused to set unsafe header "host"
index.js:63 OPTIONS https://s3.amazonaws.com/?Action=GetObject&Version=2010-05-08 403 (Forbidden)
index.js:63 Failed to load https://s3.amazonaws.com/?Action=GetObject&Version=2010-05-08: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
index.js:63 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://s3.amazonaws.com/?Action=GetObject&Version=2010-05-08'.
You might want to use the SDK, combined with the browser debugger to figure out how the SDK formats the request. In the Chrome debugger Network tab, you can copy the request as a javascript fetch. This will show all the headers you need to set. You can then use this as a basis for your non-SDK code.

Fail to load JSON file due to no 'Access-Control-Allow-Origin' is present on the requested resource [duplicate]

This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 5 years ago.
I've been trying to get data from a JSON file that's in a Github Repo. I'm using just XMLHttpRequest().
$(function() {
load();
function load() {
var fetch = new XMLHttpRequest();
fetch.open(
"GET",
"https://github.com/prvnbist/Periodic-Elements-App-Using-JSON-And-JQuery/blob/master/elements.json",
true
);
fetch.onload = function() {
if (this.status == 200) {
var elem = JSON.parse(this.responseText);`
}
}
}
});
This is the error I'm getting!
Failed to load https://github.com/prvnbist/Periodic-Elements-App-Using-JSON-And-JQuery/blob/master/elements.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s.codepen.io' is therefore not allowed access.
The code works perfectly on localhost, ofcourse but on codepen it's giving me this error which is legit for security purposes but I haven't been able to get around it.
Here's the link to Codepen - https://codepen.io/prvnbist/pen/EwOapM
You are running into the same origin policy, and the browser is suggesting using CORS to securely access GitHub. But you don't have access to GitHubs servers to make that change.
GitHub is not an API, and thus does not implement the CORS headers. The workaround is to use a proxy service like RawGit to access your files.

Categories