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

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

Related

How to make a cross domain request from javascript

var http = new XMLHttpRequest();
var url = "http://example.com/";
http.crossDomain = true;
http.withCredentials = true;
http.open("GET", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send();
console.log(http.responseText);
When i try to do a cross domain request from the javascript as seen in the code, it throws me an error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. How can i resolve that since i don't to persue solution of JSONP. Are there any other solutions from which i can resolve it. And i don't have control on the server side since its a third party server.
There is no way to read the data using purely client side code.
You need to make the request from a server, and have the client side code fetch the data from that server.
Said server will either be the same origin as the page hosting the JS or it will be one that uses CORS to grant permission to your origin.
The problem is that this request is thrown by the client rather than the server.
One way to solve this is to use a proxy, e.g. a PHP proxy, so that you actually retrieve the data via a server script (for instance using cURL) and make your JS script request your server page instead of the cross-server one.
PHP web proxies already exist, and looking here or here might give you an idea on how to achieve what you're looking for.
There is no way to make it using JS only, apart from asking the other server's owner to whitelist you, which in most cases is really unlikely.

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.

Read a Url Returning Data In Xml Format From Client Browser Without Sending Requst To Server, Using Client Side Internet

I Got An URL http://www.straitstimes.com/print/singapore/rss.xml# Which Will Return Data In XML Format And I Have to Make Use Of Client Internet For Retrieving The Data Instead Of Server Side Internet.
I Mean Even If There Wont Be Any Internet Access On The Server I Should Get The Data Making Use Of Client Internet
I Have Tried Using This Code
System.Net.WebClient webClient = new System.Net.WebClient();
strSource = webClient.DownloadString(url);
webClient.Dispose();
And Also I tried Using
XmlDocument doc = new XmlDocument();
doc.Load(url);
strSource = doc.InnerXml;
But It Didn't Help Me
And Also I Cannot Use Server For Retrieving The Data, I got To Do This From Client Browser Without Requesting To Server.
Please Suggest How Can I Do This..
Thanks
You cannot do this because the only way to achieve it is to use a javascript AJAX call, except that this RSS feed is not hosted on your site and the same origin policy restriction will prevent you for accessing it.
There are 2 possible workarounds for the same origin policy restriction:
JSONP (won't work in your case because this is XML, not JSON)
CORS
So this will only work if the remote server supports CORS. And of course only in browsers that support CORS.

How can I get HTTP response header using JS?

I tried so many tutorials online but everything I try is really old and fails - I can't even create an XMLHTTPRequest object!
I just want to get the header from google.com - how can I do that?
You would use xhr.getResponseHeader() to get a single header, or xhr.getAllResponseHeaders() to read all of the headers from an XMLHttpRequest response.
The reasons this won't work for you:
XMLHttpRequest is case sensitive. If you are using HTTP in all caps, it will fail.
Unless you are a google employee adding code to google.com, your request falls victim to the same origin policy. You'll have to use your server as a proxy to get headers from a google request.
You cant simply do this by JS. You'll have to use AJAX and do a server request to PHP,ASP, Java or whatever. The XMLHTTPRequest should do it - if you really want to do it manually. But it will really not work with foreign domains, so you are forced to do the XMLHTTTPRequest to a page on your server which will deliver the header.

Twitter API Error: 'internal server error'

I tried to use Twitter API to post a tweet using Javascript. Details Below
Base String
POST&http%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&oauth_consumer_key%3DXXXXXXXXXXX%26oauth_nonce%3D9acc2f75c97622d1d2b4c4fb4124632b1273b0e0%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1305227053%26oauth_token%3D159970118-XXXXXXXXXXXXXXXXXXXXXXX%26oauth_version%3D1.0%26status%3DHello
Header
OAuth
oauth_nonce="9acc2f75c97622d1d2b4c4fb4124632b1273b0e0",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1305227053",
oauth_consumer_key="XXXXXXXXXXXXXXXXX",
oauth_token="159970118-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
oauth_signature="IWuyoPJBrfY03Hg5QJhDRtPoaDs%3D",
oauth_version="1.0"
I used POST method with body "status=Hello"
But i get a INTERNAL SERVER ERROR.. IS there any mistake on my side ?? Thanks in advance.
Javascript code used
h is the header given above
tweet="Hello"
encodeURLall is user defined which is working in all other occasions.
var xhr = new XMLHttpRequest();
xhr.open("POST","http://api.twitter.com/1/statuses/update.json", false);
xhr.setRequestHeader("Authorization",h);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 )
{
console.log("STATUS="+xhr.status);
console.log("RESPONSE="+xhr.responseText);
}
}
xhr.send("status="+encodeURLall(tweet));
}
You cannot access Twitter's site using an XMLHttpRequest, due to Same origin policy. Use JSONP instead or a server-side proxy (call your own server that redirects your request to Twitter).
BTW, what does encodeURLall() do? Shouldn't you just use encodeURIComponent?
Update: To quote Google:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
Please read on there to see which settings you should change in order to make this work.

Categories

Resources