Ajax - "Access-Control-Allow-Origin" Error - javascript

I'm trying to work with the Livestream API to see if a certain channel is live but keep getting this error:
XMLHttpRequest cannot load http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft. Origin http://www.webdevstl.com is not allowed by Access-Control-Allow-Origin.
Do I need to run it through PHP or am I doing something wrong in my ajax call? It's pretty straight forward code:
function getActive(){
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
console.log(json);
}
}
xmlhttp.open("GET", "http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
getActive();

You're running into restrictions imposed by the Same Origin Policy. In short, AJAX calls to a different domain are prohibited and will fail - unless explicitly permitted by the remote host.
You need to either use JSONP (mostly applicable to data returned by APIs) or proxy the request through your own server/domain.
CORS would also be an option, but that assumes you having access to the remote server's config.

Related

How to set CORS header in an AJAX call with pure JavaScript that is hitting other rest service?

I am having following JS function that gets called on html page load. When the page loads I see following error in the Firefox console logs.
Firefox Console Log:
"NetworkError: 403 Forbidden - http://localhost:8080/publicKey/lookup/TRUUS2"
TRUUS2
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/publicKey/lookup/TRUUS2. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
publickey.js
function loadPublicKey() {
var xmlhttp = createCORSRequest('GET', 'http://localhost:8080/publicKey/lookup/TRUUS2');
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
alert(this.responseText);
document.getElementById("keyDiv").innerHTML = this.responseText;
}
};
}
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
return xhr;
}
I have already added xhr.setRequestHeader("Access-Control-Allow-Origin", "*") statement to fix the CORS issue but no luck. I am looking for pure JS implementation.
Note: I am able to hit the http://localhost:8080/publicKey/lookup/TRUUS2 URL successfully through Postman and getting the response as well. No issues there.
Not sure what am I missing. Please guide.
Based on the input provided by Rory, I removed the xhr.setRequestHeader("Access-Control-Allow-Origin", "*") from the JS and added snippet #CrossOrigin(origins = "http://localhost:8084") in my controller and that solved the problem.
#CrossOrigin(origins = "http://localhost:8084")
#RestController
public class PublicKeyLookupController {
//code removed for brevity
}

Cross-subdomain request

I need to make a cross subdomain request. There is a classic asp site which create an XMLHttpRequest to my PL/SQL Oracle webpage.
The asp site has the domain: test/site.asp and the PL/SQL webpage has the domain test:7779/site... so the top level domain is the same
This is my XmlHttpRequest:
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onload = function() {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
createChart(divID, xmlHttp.responseText, counter);
} else {
console.error("error");
}
}
};
xmlHttp.open( "GET", theUrl);
xmlHttp.setRequestHeader( "pragma", "no-cache" );
xmlHttp.send( null );
No error occurs in IE11, but in Chrome:
XMLHttpRequest cannot load http://test:7779/site
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://test' is therefore not allowed access.
The response had HTTP status code 501.
Is there a solution to make a cross subdomain request? Maybe with an iframe in my asp site, to get the content?
UPDATE:
I know tried to set the document.domain at both sides to the same: test. But this also didn't solved the problem.
My suggestion is, why dont you use MSXML2.ServerXMLHTTP object, as you have Classic ASP in hand? So that XMLHttp request will be sent from server to server and not from browser.
You can use it like this,
Dim xmlhttp
Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.setTimeouts 30,500,1000,1000
xmlhttp.Open "GET", "http://yourlink" & time, false
On Error Resume Next
xmlhttp.Send
If Err.Number Then
getBBstatus = "Could Not Retrieve Data"
Err.Clear
Else
getBBstatus = xmlhttp.ResponseText
' Do something with the response here
End If
On Error Goto 0
Set xmlhttp = nothing
Hope it helps, thanks.

Ajax Yelp API Call from Javascript

I'm trying to make a call to the Yelp API from JavaScript, but getting an error. Below is my code. I believe I will have to use Oauth, but I don't know where should I put it in the header.
function doAjax(){
var xhr = new XMLHttpRequest();
var url = "http://api.yelp.com/v2/searchterm=cream+puffs&location=chicago";
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var some = JSON.parse(xhr.responseText);
}
}
xhr.open('GET', url, true);
xhr.send();
}
The problem is that you are trying to access a resource that is on a different domain from your application. In this case your application resides on http://fiddle.jshell.net and the resource is at http://api.yelp.com.
CORS is one way to get around this, see here:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

How to overcome the http request status zero in a local machine

There is a lot of same questions but i cannot find the answer so i am reposing the same question.I am receiving an json request using java script
var request = null;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
return null;
}
request.open("GET", url, true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
}
} else
alert(request.status);
}
I am receiving an status code zero while i receive the request the javascript runs on apache server and json request will be received from tomcat server everything is local . can any one tell me how to over come it.
Note: i cannot use any framework.
I suspect that you are violating the same origin policy restriction that is built in browsers. This restriction prevents you from sending cross domain AJAX requests. So for example if the page containing the AJAX call is hosted on http://localhost/example.htm and you are trying to send an AJAX request to http://localhost:8080/somescript you won't be able to do so because the domains do not match (different ports).
The best way to ensure that your AJAX requests work is by only using relative urls:
request.open("GET", "/somescript", true);

Access is denied. JavaScript error on request to secured page

On page SomePage.aspx, by JavaScript code (XMLHttpRequest) I call SecuredPage.aspx used next code:
var httpRequest = GetXmlHttp();
var url = "https://myhost.com/SecuredPage.aspx";
var params = "param1=" + document.getElementById('param1').value +
"&param2=" + document.getElementById('param2').value;
httpRequest.open("POST", url, true);
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
//Call a function when the state changes.
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
alert(httpRequest.responseText);
}
}
httpRequest.send(params); // HERE ACCESS IS DENIED.
//---------------------------------------------
function GetXmlHttp() {
var xmlhttp = false;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
// Code for Internet Explorer.
{
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
It throws an Access is denied error. If send to http (http://myhost.com/SecuredPage.aspx), it works fine.
How is it possible to resolve this problem?
If you wish to fetch an HTTPS page via Ajax you need to do it from an HTTPS page on the same domain, there is no other way, as long as you use Ajax. This is because of the same origin policy.
That said, there are plenty of ways to do this not using Ajax, for instance you can use frames.
Another way is to use JSONP, but this requires that you are fetching, well, JSON :)
A third way, that tends not to be very useful for production websites, but still can be fun to tinker around with, is to use YQL as a proxy.
Lastly you can always set up a serverside proxy of your own, so that you call an HTTP address that fetches the HTTPS page and sends it on, but this is rarely a good solution if it can be avoided.
This is because the browser considers http and https as 2 different sites/domains, and therefore you have to adhere to the same origin policy.
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
One way to solve it is using jsonp.
As it's been said, your problem is that your browser sees this as a cross domain request. Another way to accommodate this is to set up a crossdomain.xml file like this:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="myhost.com" />
<allow-access-from domain="ourhost.com" />
<site-control permitted-cross-domain-policies="master-only" />
</cross-domain-policy>
I'm not an expert on this method, but I have used it successfully. Other domains can be added by adding more allow-access-from tags. You may need to do some fiddling. YMMV.

Categories

Resources