I am running an API on my local server port 8000. In other words, 127.0.0.1:8000/api returns JSON data when the method is get. I know this because if I make an ajax request from one of its views, I get the correct return data.
Now, I am trying to get this API to work with 3rd party websites as well. So I built another app, and ran it on port 8080. In other words, going to 127.0.0.1:8080 runs the following JS code:
(function() {
$.ajax({
url: 'http://127.0.0.1:8000/api/',
type: 'GET',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin': '*'
},
success: function( json ) {
console.log('Success');
},
error: function( req, status, err ) {
console.log(req + status + err);
}
});
})();
Note: I ran this code with the API running on port 8000. However, I get this error in my console:
[Error] XMLHttpRequest cannot load http://127.0.0.1:8000/api/. Origin http://127.0.0.1:8080 is not allowed by Access-Control-Allow-Origin.
What is going on? How can I fix this, and test my API on my local server? Any help will be greatly appreciated!
You are having CORS issues. That means your Browser is protecting you from foreign Resources. Depending on the JS Framework you use, there are workarounds for this. The Most Common is jsonp, which allows you to create Cross Domain requests (See https://www.sitepoint.com/jsonp-examples/)