httprequest not working when calling my page from another computer [duplicate] - javascript

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 4 years ago.
I have a single html page which is deployed in xampp page which has a script tag where i use XMLHttpRequest to call a service url to get json data.
This only works when i call the page with http://localhost/mypage
But when i call the same page from another computer http://ipadress/mypage it throws an error.
“No 'Access-Control-Allow-Origin' header is present on the requested
resource”
I tried using JSONP solution but that didn't work either
Note that i can only manipulate client-side code (javascript), i have no control on the service i'm calling
Why does it work with localhost but it doesn't work with ipadress?
And what are the alternative solution if there are any ?
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var result = JSON.parse(this.responseText).result;
document.getElementById("data").innerHTML = result + "%";
}
};
var url = "www.url.com";
xhttp.open("GET", url + "/data.json", true);
xhttp.setRequestHeader("content-type", "application/json");
xhttp.send();

So you trying to retrieve data form a different domain than you application is actually from. You have to specify for your served page that it is allowed to do that.
Depending on how you build/serve your html page/the content (json) this is different.
Usually this is done by setting it in the header before the response is send to the client back.
Using PHP: header('Access-Control-Allow-Origin: *');
Using apache .htaccess file (for more files, eg: if you don't use server side scripts): Header set Access-Control-Allow-Origin "*"
Better would be not to specify * but the origins the application should have access to.
Further reading:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Related

Issue with JSON.parse() from URL

I have this code trying to obtain prices from Bloomberg but I can't make it works.
This is the URL:
https://www.bloomberg.com/markets2/api/intraday/BACHOCOB:MM?days=1&interval=2&volumeInterval=15
And my failure code:
<p id="quote"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var price= JSON.parse(this.responseText);
document.getElementById("quote").innerHTML = price[0]["previousClosingPriceOneTradingDayAgo"];
}
};
xmlhttp.open("GET", "https://www.bloomberg.com/markets2/api/intraday/BACHOCOB:MM?days=1&interval=2&volumeInterval=15&currency=MXN", true);
xmlhttp.send();
</script>
Thanks in advance.
What is the excat error message your getting? Is it something like "No 'Access-Control-Allow-Origin' header is present on the requested resource"?
If so, that has nothing to do with JSON.parse as it is a security measure against XSS (Cross Site Scripting). You cannot request web responses from other domains if the server doesn't allows it explicitly.
See https://en.wikipedia.org/wiki/Cross-origin_resource_sharing for more information.
As an additional note: you can work around this. Even if you have no access to the server you could make use of a proxy server, that gets the request for you and uses the appropriate response header to allow your script to make the response. An example would be "corsproxy" from npm (No experience with it. Just a quick google search).
You can get value as below by adding jQuery to your project
$.ajax({
type: "GET",
url: "https://www.bloomberg.com/markets2/api/intraday/BACHOCOB:MM?days=1&interval=2&volumeInterval=15",
dataType: "json",
success: function(getPrice) {
$('#quote').append(getPrice[0].previousClosingPriceOneTradingDayAgo);
}
});
It seems CORS is an issue. Since you are using GET request to an SSL URL, it expects you to send this request from an HTTPS origin. To test your script, use Chrome Browser with CORS extension installed. You shall see the result.
In short, you need an HTTPS origin URL, you might want to try CURL with PHP for a possible solution if SSL is an issue !

"No 'Access-Control-Allow-Origin' header is present on the requested resource." when making "GET" request

I'm using an HTTP-request in order to get Google's autocomplete suggestions, here's what inspired me to do so:
You can make a GET request to the following URL:
http://suggestqueries.google.com/complete/search?client=chrome&q=cats
Where "client" param is your browser's name (works with most but you may pass >the same type disregarding what the user is currently on and it will still work).
And "q" param is your search string.
This will return you a list of suggested items which you can then put into a jQuery autocomplete plugin or build your own (you can't just get the whole >google dropdown interface to popup with a single function sadly :) )
(src: Add Google autocomplete to Google search bar?)
I'm using this function to get Google's response text:
function httpGetAsync(theUrl, getGoogle){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
getGoogle(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
However, when the funtion is executed, CORS seems to prevent me from getting a response: Failed to load http://suggestqueries.google.com/complete/search?client=chrome&q=xx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
Is there a way of adding an 'Access-Control-Allow-Origin' header to the resource?
You cannot make a request to another domain from the users browser, unless the source has the Access-Control-Allow-Origin header for your domain. In conclusion, you cannot make the request on the users part without using some kind of proxy, like this one:
https://cors-anywhere.herokuapp.com/
Example:
url: https://cors-anywhere.herokuapp.com/https://google.com

Unable to retrieve data from http site to https using XMLHttpRequest()

I have a site hosted on https:// in which I want to pull data from the site which shows the properties of the shares. The URL which returns the data is:
http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
The code which I have developed to get the data is as follows:
function GetSharesUpdate(){
// makeing AJAX calls to the web service for getting the share update
var xhr = new XMLHttpRequest(); // Set up xhr request
xhr.open("GET", "http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191", true); // Open the request
xhr.responseType = ""; // Set the type of response expected
xhr.send();
// Asynchronously wait for the data to return
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
var tempoutput = xhr.responseXML;
alert(tempoutput);
}
}
// Report errors if they happen
xhr.addEventListener("error", function (e) {
console.error("Error: " + e + " Could not load url.");
}, false);
}
I am getting the error on the statement xhr.send(); which is as below:
Mixed Content: The page at 'https://[SiteUrl]' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint
'http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191'.
This request has been blocked; the content must be served over HTTPS.
If I change the URL to https i.e.
https://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
then xhr.send(); is executed without any error but I am getting xhr.responseXML null.
What should I make changes in my code to make it working?
The first problem is you are doing ajax request to non-https domain but your domain has SSL installed.
The second problem is Cross origin request CORS, you will have this problem even you solve first (ie. even you try ajax request from non-http domain).
Since you are requesting data from another website this is most likely to happen unless the requested server is configured to serve requests for you domain
To solve this you need to call the data from your server(proxy server) or have the requested server configured to allow requests from your domain.
See more - https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Whats the difference between calling a URL using XMLHttpRequest and a Form?

I'm using static html/javascript pages (no php, etc.)
I have a static HTML web page. When the page loads, it makes an XMLHttpRequest to a target server on another domain, waits for the response, and parses the response JSON.
function executeRequest() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var response = JSON.decode(xhttp.responseText);
alert(response.access_token)
alert(response.expires_in)
}
};
var tmpURL = "https://target.url.com/oauth2/access_token"
xhttp.open("POST", tmpURL, true);
xhttp.send();
}
XMLHttpRequest cannot load [target.url.com] No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Origin 'https://local.url.com' is therefore not allowed access.
To rule out a problem with CORS, I can request the URL with a form. When the user clicks the Submit button, it brings a successful response.
<form method="POST" action="https://target.url.com/oauth2/access_token">
... form inputs here
<input type="submit" value="Submit form">
</form>
Why is the target server responding differently to the xmlHttpRequest than the Form?
You have a CORS issue.
XMLHttpRequests are subject to CORS rules.
<form method="POST" action="http://xxx"> posts done purely with HTML are not subject to CORS rules.
It's as simple as that.
Part of the reason this cross origin form post is allowed is that the browser will change the browser window to display the response from the form post so the cross origin site controls what happens next. That is not the case with XMLHttpRequest where the requesting page controls what happens next as no page is automatically loaded or displayed after an XMLHttpRequest. So, it's easier to cause mischief with XMLHttpRequest than it is with a form post.
See Cross Domain Form POSTing for some further explanation.

XMLHttprequest not working the twitch.tv api

So I've been trying to access the twitch.tv api but every time i go to make a request i keep on getting the error:
"XMLHttpRequest cannot load https://api.twitch.tv/kraken/streams/normalice. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access."
I'm currently using the live-server package during the development process other wise I'm just using html, css, javascript. Here is my javascript:
var req = new XMLHttpRequest();
var url = 'https://api.twitch.tv/kraken/streams/normalice';
req.open("GET", url, true);
req.send();
req.onreadystatechange = function () {
if (req.status == 200 && req.readState == 4){
// do stuff here
console.log('hurray it worked');
}else{
console.log(req.statusText);
console.log(req.responseText);
}
}
Does anyone have any ideas as to why am I encountering this error?
The Twitch.tv API doesn't support CORS. You need to use JSON-P (aka JSONP) to work around it. Read more about that in the Twitch.tv API docs. There is a prior answer on how to make a JSONP request with native JavaScript that may be useful.

Categories