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.
Related
I am trying to check wheater the URL of another domain exists or not from my domain('https://radiusofficefurniture.ie') using Javascript like :
var request = new XMLHttpRequest();
request.open('GET', 'https://www.mozilla.org', true);
request.onreadystatechange = function(){
if (request.readyState === 4){
if (request.status === 404) {
alert("Oh no, it does not exist!");
}
}
};
request.send();
But the issue of CORS policy occurred. The error is like this:
Access to XMLHttpRequest at 'https://www.mozilla.org/' from origin 'https://radiusofficefurniture.ie' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Kindly someone help me how can I check if the URL of other domains exists using javascript?
Actually, I have to add an HTML tag to my site if the URL of other domains exists.
The easiest way is to use a CORS Proxy (if you want to avoid any extra code). You can find a couple here, and they're all relatively easy to set up.
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¤cy=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 !
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
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
I tried to manage editing the template but I'm still not able to send email, I'm creating an subscription box, here's my code so far:
var x= document.getElementById("emailtxt").value;
var uploadFormData = new FormData();
uploadFormData.append("email", x);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://realfashionstreet.com/Emailme.php',true);
xhr.onload=function() {
alert(this.status);
if(this.status==200) {
console.log('data sent');
alert(xhr.responseText);
} else {
//alert(this.status);
alert('Something Went Wrong, Try Again Later!');
}
};
/*xhr.addEventListener("load", function () {
document.getElementById('skm_LockPane').className= 'LockOff';
}, false);*/
xhr.send(uploadFormData);
return false;
}
Here's the box I'm getting :
http://realfashionstreet.com
It's just not showing any error or any response and also not sending email, but I think that site template doesn't allow to use php files if anyone have any other idea on how to send email using javascript…
Thanks
You can't for security reasons. See the same origin policy for JavaScript.
There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended.
The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted.
You're missing the www. in the request, this is causing a cross domain policy violation. This is the error I see in the console.
XMLHttpRequest cannot load http://realfashionstreet.com/Emailme.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.realfashionstreet.com' is therefore not allowed access. Default.asp:1
Ensure the URLs for the page and the XHR request have the exact same domains. Including subdomains like www