How does JQUERY do CORS (Cros Origin Requests)

How does JQUERY do CORS (Cros Origin Requests)
0.0 0

#1

Hello

I’ve been trying for hours to complete the Local Weather challenge without using JQUERY for the API communication but my “Vanilla” Javascript code fails because it violates the “Cross Origin Policy” yet JQUERY code works perfectly.

I really want to understand what goes on under the hood partly because I’m stubborn and partly because relying on libraries without understanding the fundamentals seems foolish to me.

So how does JQUERY do it and how can I do it/
.
.
.

My Code That Fails

function Start()
{
	//var corsProxy = "https://crossorigin.me/";
	var url = "http://api.openweathermap.org/data/2.5/weather?lat="+"35"+"&lon="+"139"+"&appid=9de5e5c188e423ac7e6bda7f5f1d761a";
	
	var xhttp = new XMLHttpRequest();
	xhttp.onreadystatechange = APICallback;
	xhttp.open("GET", url);
	xhttp.withCredentials = true;
	xhttp.send();
}

function APICallback()
{
        console.log(this.status);
}

.
.
.
JQUERY Sorcery That Works

function Start()
{
	var url = "http://api.openweathermap.org/data/2.5/weather?lat="+"35"+"&lon="+"139"+"&appid=9de5e5c188e423ac7e6bda7f5f1d761a";
	$.getJSON(url, APICallback);
}


function APICallback(data)
{
	 console.log(data.weather[0].main);
}

#2

I think the getJSON() method in jquery adds the &callback=? parameter to the request, this is necessary for cross domain operation but not supported by all servers unless configured.

There are all sorts of gotchas though, such as the XMLHttpRequest used by jQuery isn’t supported by Microsoft browsers of old so a fallback of XDomainRequest is required. It’s a real pain in the backside.

Personally I just try and use HTTPS wherever possible for both the website url and the server url that i’ll be contacting as this gets round most issues.