Change CORS policy with javascript alone? [duplicate] - javascript

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

Related

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.

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

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.

How do I load a static, plaintext json file into Javascript with a GET request? [duplicate]

This question already has answers here:
Get JSON data from external URL and display it in a div as plain text
(7 answers)
Closed 6 years ago.
This is the one I am testing with, specifically:
static json data
I have run into many cross-site request errors, though I don't see how this should be different than requesting an image that is statically hosted on the same site, which I can easily load into my test html file.
I have tried the following:
$.getJSON('http://anyorigin.com/get?url=maxcandocia.com/static/blog/test_output3.json&callback=?',
function(data){
$('#output').html(data.contents);
});
var network_data
$.getJSON("http://maxcandocia.com/static/blog/test_output3.json",
function(data){
network_data = data.contents;
})
In general, you can't access a resource on another origin (in essence domain-port combination) through JavaScript unless that origin explicitly allows you to through the use of specific headers, specifically the Access-Control-Allow-Origin.
It seems that anyorigin.com, the service that you're using, for some reason fails to redirect correctly; this does not appear to be your fault, but something wrong with the service. I would recommend that you try some other, equivalent service, such as https://crossorigin.me/ (just add https://crossorigin.me/ in front of the URL):
var network_data;
$.getJSON("https://crossorigin.me/https://maxcandocia.com/static/blog/test_output3.json",
function(data){
network_data = data.contents;
})
If you control the server yourself, it would be better to just set up the server to send the Access-Control-Allow-Origin header for your JSON file.
Access-Control-Allow-Origin is not an issue with your code. It means you have an issue with security policies.
If you own maxcandocia.com you need to adjust the headers to allow your origin (where you're running the script). If not, you have no chance here unless they change their policies for you (unlikely.
You would instead be looking for a server-side solution, such as what Frxstrem has suggested. Or if you own the script send back this header with the origins you require:
Access-Control-Allow-Origin: http://yourorigin.com http://maxcandocia.com https://maxcandocia.com
I have an in depth answer here on using json with jquery: https://stackoverflow.com/a/17768384/2376468

Why does the browser not allow CORS when server side script could easily do this? [duplicate]

This question already has answers here:
Why does Ajax give me a cross origin error when I can make the request from PHP?
(3 answers)
Closed 7 years ago.
Under the same-origin policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.
But I did not get the essence of it. If I cannot make a cross domain request from my browser, I will make it through my PHP script. It will work fine. Isn't it?
So, instead of doing the following:
var xhr = new XMLHttpRequest();
var url = "https://www.google.com/finance/converter?a="+amount+'&from='+from+'&to='+to;
if(xhr) {
xhr.open('GET', url, true);
xhr.onload = function() {
// Handle
};
xhr.send();
}
which will result in :
XMLHttpRequest cannot load https://www.google.com/finance/converter?foo. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin abc.com is therefore not allowed access.
I could do via my own php script by sending a ajax request like:
$.ajax({
method: "GET",
url: "./bin/http/CimmClient.php",
dataType: 'html',
data:{
a: amount,
from: from,
to: to
}
})
.done(function(data, textStatus, jqXHR ){
// Handle
})
And this works perfectly fine. PHP only sends an HTTP request to another domain and then sends back the response to javascript.
So, what in principle was the difference? Why does the browser prevent sending cross domain HTTP request, when php/java/others would easily allow this?
These limitations are not implement to prevent YOU to use any kind of service, these are implemented in order to prevent a malicious code that you are not aware of to act ON YOUR BEHALF.
So, if YOU WANT to, you can obtain the data - e.g. using server side script, and that is OK. But if you load a malicious web page to your browser, or a web page that was infected by malware, its scripts are not able to act on your behalf and send requests to third party services.
It could be argued that there are legitimate use cases for such cross origin access, but the security on the Internet is a big thing and it is considered before comfort of developers.
For example, assume you have an online bank that uses cookies to store information on users' opened authenticated sessions. You log into a bank and check your accounts. You leave this tab open in your browser and you access a malicious website. That website sends Ajax to the bank asking for a list of transactions using a simple GET request. Your browser will invoke the GET request and send session cookies to the bank and the bank will reply with a sensitive information about your accounts. The malicious script then uploads the data to its server. Once the cross origin access is forbidden, this scenario is no longer possible.

Cross Origin Resource Sharing (CORS) and Javascript

As an example case let's take this url: http://api.duckduckgo.com/?q=computer&format=json (CORS not enabled on this server!)
We can access the contents from this URL from any popular browser as a normal URL, browser has no issues opening this URL nor the server returns any error.
A server-side language like PHP/RoR can fetch the contents from this URL without adding any additional headers or special server settings. I used following PHP code and it simply worked.
$url='http://api.duckduckgo.com/?q=computer&format=json';
$json = file_get_contents($url);
echo $json;
I just started working in javascript framework, AngularJS. I used following code...
delete $http.defaults.headers.common['X-Requested-With'];
var url="http://api.duckduckgo.com/?q=computer&format=json";
$http.get(url)
.success(function(data) {
$scope.results=data;
})
With above AngularJS code, I received following error:
XMLHttpRequest cannot load http://api.duckduckgo.com/?q=computer&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
AngularJS uses JQuery so I tried the same in JQuery with following code:
var url="http://api.duckduckgo.com/?q=computer&format=json";
$.getJSON(url , function( data ) {
console.log(data);
});
This also produced the same error as did AngularJS code.
Then my further research brought me to the point that it's actually not specific to JQuery and AngularJS. Both of these inherit this issue from Javascript!
Here is an excellent resource with explanation of what CORS is and how to handle with it: http://enable-cors.org/index.html.
And also W3C has it official CORS specification: http://www.w3.org/TR/cors/
So my question is not what CORS is. My question is
My understanding is that whether it is a web browser or it is PHP/RoR or it is Javascript frameworks, all make requests to a URL via the same http or https, right? Certainly, yes. Then why http has to be more secure when requests come from javascript? How does http and server know that request is coming from javascript?
When a web browser can open a URL and PHP/RoR (or any server-side language) can access that URL without any extra settings/headers, why can't AngularJS, JQuery (or in a single word javascript) access that URL unless the server has set Access-Control-Allow-Origin header for requesting root?
What's that special feature (that PHP/RoR have and) that is missing in Javascript so that it can't access the same URL in the same browsers that can open that URL without any issue from their address bars?
Just to mention that I am basically an iOS developer and recently started to learn web development, specially AngularJS. So I am curious about what's all this going on and why!
It's disabled from javascript for security reasons. Here's one scenario:
Assume Facebook has a "post message on timeline" api that requires the user to be authenticated.
You are logged into Facebook when you visit badsite.com.
badsite.com uses javascript to call the Facebook api. Since the browser is making a valid request to Facebook, your authentication cookie is sent, and Facebook accepts the message and posts badsite's ad on your timeline.
This isn't an issue from a server, because badsite.com's server doesn't have access to your Facebook authentication cookie and it can't forge a valid request on your behalf.
You remember that all javascript request is handled by browser. So browser detect cross-origin request is easy.
Request from javascript has no difference with PHP/RoR, it is only rejected by browser.
Server code can accept cross-origin javascript request by header "Access-Control-Allow-Origin" because before reject javascript request, browser will send a request "OPTIONS" to server to ask header "Access-Control-Allow-Origin" on response. If value is match with current origin, browser will accept javascript request and send to server.
All browser are implement this policy Same Origin Policy
Please read http://en.wikipedia.org/wiki/Cross-site_scripting, you will get the reason why its prohibited for JavaScript.

Categories