Making API connection from local drive - javascript

I am trying to access website APIs from my local drive to work with their data. I followed the JSON doc on MDN (https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON) and it worked great. I can access and get the same data as shown in the doc with the code below. However when I change to a different website's API, I get an "Access-Control-Allow-Origin" error. For example if I use (http://quotesondesign.com/wp-json/posts).
After doing some search online, it seems to have to do with CORS setup on some servers. I read through the CORS doc (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) but still having trouble with it.
Some search results also mentioned a work around like using proxy but I am reluctant to use it as it seems unwieldy. I also tried Jquery and AJAX but I still get the same error when it tries to open the request.
<script>
var header = document.querySelector('header');
var section = document.querySelector('section');
var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseTYPE = 'json';
request.send();
request.onload=function() {
var superHeroes = JSON.parse(request.response); //Parse the files
populateHeader (superHeroes);
showHeroes(superHeroes);
}
...
When I say local drive, I mean I saved the html code in a notepad file on my C:\document drive and running the file there.
Any advice? Thanks.

Web browsers agree with the server CORS policy by default. Developers sometimes disable security protections to test things out. Be sure to turn it back on for normal browsing.
With Chrome on windows, this flag enabled that API to work for me:
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
This works well in a shortcut for special uses.
More info on bypassing CORS in Chrome and FireFox here:
https://pointdeveloper.com/how-to-bypass-cors-errors-on-chrome-and-firefox-for-testing/
Update: In Firefox, the about:config option to disable "strict_origin_policy" is limited. So to get this working, you can try the CORS Everywhere add-on. This worked for me on Firefox 52.8.
The CORS Everywhere icon will toggle green after you click it, which enables CORS.

Related

XMLHttpRequest in ChromeCast Custom Receiver does not send Cookie header to Same Domain

Using XMLHttpRequest I would like to send the Cookie to the same domain via ChromeCast custom receiver. I'm using the following code, but when I look at the headers in the Request, the Cookie header does not appear.
Is there a way to send a request using cookies with XMLHttpRequest via ChromeCast?
$.cookie("a", "test",{expires: 7, path: "/"});
var r = new XMLHttpRequest();
r.open('GET', '/api/checksession', true);
r.withCredentials = true;
r.send();
Thanks.
You may refer with this thread which suggested to make sure that the manifest.json permissions are setup properly.
From this documentation, you have to properly set the cross site domain request permission in the manifest.json of your chrome extension. When done properly, the cookies who are already set for the targeted domain will be sent along with the request you are making to that domain.
You have to be especially careful when playing with localhost:port_number. You will need to specify that domain in full in the manifest.json for it to work. I ended up with awkward behaviors when my localhost domain was NOT specify in full.

Why does XMLHttpRequest/XHR and Fetch API work locally in Firefox 51?

Update: As of Sep 7 2019 (Firefox 79), this is no longer the case. Must have been a mistake in FF 51.
This question is for the Firefox devs/pros out there. I can't find any info on this.
I've longed assumed XMLHttpRequest (XHR) and similar APIs such as the new Fetch API are not supposed to work locally (i.e. file uri), and only work on http or https uri scheme. It's supposed to be some big security risk.
In the past, the only way to circumvent this in Firefox was changing security.fileuri.strict_origin_policy to false in about:config. To my surprise, I can use both XHR and Fetch API without changing that setting in the latest Firefox.
Why does it start working out of nowhere on Firefox 51.0.1? Is this a bug, a new standard, or some vendor-specific thing? Is Chrome going to follow along with this?
To see what I mean, create an index.htm with some JS code and a test.txt with some text, and open the index.htm in Firefox locally.
Put this in the HTML:
<script>fetch("test.txt").then(function(response) {
return response.text();
}).then(function(text) {
alert(text);
});</script>
In Firefox it should show an alert box with the contents of the text file. In Chrome/Canary, it will complain:
Fetch API cannot load file:///R:/test/test.txt. URL scheme must be "http" or "https" for CORS request.

CORS response not received on different computers

This is my first question on SO, but you have all helped me enormously in the past from existing posts - so thank you!
I am working on a Web/Database system using localhost through Xampp, but need to backup sql file to my one&one online server. I am using CORS for cross-domain with js to make the backup and it works on my PC, but not my clients. The request onload works for us both, as the files are saved, but my client does not receive the response message to confirm it has saved!! Anyone know why this might be - we are both running IE9 and same xampp versions.
Code I am using for CORS request is:
var request = new XMLHttpRequest();
request.open('POST', "http://www.mysite/Backups", true);
request.onload = function()
{
if (request.status === 200)
{ //response functions here}
request.send("Content="+backupContent);
}
Hope this is in the correct question format - its my first time remember!
I had a year ago a really similar problem with IE. Your client is using IE, that means they are quite big and serious, so I bet they also have specific settings for IE security.
Go to your IE security preferences and restrict everything you can - I cannot tell you exactly the name of the property, I have no explorer anymore, but with this you can reproduce this behaviour.
How to solve the issue? Usually they don't agree on changing their security settings, so the only way that worked for me is using JSONP instead of CORS. I know: not modern, uglly... But that works.
This is just a guess, I trust that everything is done correctly on your side.

Access to restricted URI denied using AngularJS and PHP on server side [duplicate]

Access to restricted URI denied" code: "1012 [Break On This Error]
xhttp.send(null);
function getXML(xml_file) {
if (window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest(); // Cretes a instantce of XMLHttpRequest object
}
else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP"); // for IE 5/6
}
xhttp.open("GET",xml_file,false);
xhttp.send(null);
var xmlDoc = xhttp.responseXML;
return (xmlDoc);
}
I'm trying to get data from a XML file using JavaScript. Im using Firebug to test and debug on Firefox.
The above error is what I'm getting. It works in other places i used the same before, why is acting weird here?
Can someone help me why it's occuring?
Update:
http://jquery-howto.blogspot.com/2008/12/access-to-restricted-uri-denied-code.html
I found this link explaining the cause of the problem. But I didn't get what the solution given means can someone elaborate?
Another possible cause of this is when you are working with a .html file directly on the file system. For example, if you're accessing it using this url in your browser: C:/Users/Someguy/Desktop/MyProject/index.html
If that then has to make an ajax request, the ajax request will fail because ajax requests to the filesystem are restricted. To fix this, setup a webserver that points localhost to C:/Users/Someguy/Desktop/MyProject and access it from http://localhost/index.html
Sounds like you are breaking the same origin policy.
Sub domains, different ports, different protocols are considered different domains.
Try adding Access-Control-Allow-Origin:* header to the server side script that feeds you the XML. If you don't do it in PHP (where you can use header()) and try to read a raw XML file, you probably have to set the header in a .htaccess file by adding Header set Access-Control-Allow-Origin "*". In addition you might need to add Access-Control-Allow-Headers:*.
Also I'd recommend to replace the * in production mode to disallow everybody from reading your data and instead add your own url there.
Without code impossible to say, but you could be running foul of the cross-site ajax limitation: you cannot make ajax requests to other domains.

XMLHttpRequest cannot load URL. Origin not allowed by Access-Control-Allow-Origin

I want to make a small website that uses xml data from another domain. (Weather data from Weather Underground: www.wunderground.com). I am using just html and javascript, and writing it all in Visual Studio Express 2012 for Web.
I make and send the xml request as follows:
url = "http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.xml";
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
The problem is that I get the following error in the Google Chrome (version 29.0.1547.66) developer console:
XMLHttpRequest cannot load http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.xml. Origin http://localhost:49933 is not allowed by Access-Control-Allow-Origin.
Or this on Internet Explorer (version 10.0.8) console:
SEC7118: XMLHttpRequest for http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.xml required Cross Origin Resource Sharing (CORS).
As I understand it, CORS (http://enable-cors.org/) needs effort by both the client and the server to work. I want to assume that the Weather Underground API knows what it is doing and has enabled things appropriately, such as setting the response header to include 'Access-Control-Allow-Origin: *', and I know that I get the same problems when I try the same code using another API provider (World Weather Online). So I think this is something I should be able to fix in my client code.
Another SO answer where the suggestion is to fix the server-side header:
CORS with XMLHttpRequest
I have tried to find answers, but don't understand articles such as:
http://dev.opera.com/articles/view/dom-access-control-using-cross-origin-resource-sharing/
http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/
Use Ajax with JSONP if you want in jquery
For javascript see here , http://developer.chrome.com/extensions/xhr.html and http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html
Use .json format data rather than .xml to make your application simpler and faster i.e http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.json

Categories

Resources