BrownChiLD BrownChiLD - 3 months ago 11
JSON Question

Javascript weird Fetch() issues, fails on a specific JSON data/format

I have the following code using fetch

var url1 = 'http://jsonplaceholder.typicode.com/users';
var url2 = 'http://teaconcepts.net/temp/api_test.php';


fetch(url1)
.then(function (result){
console.log("Result received");

return result.json();
}).then(function(data){
// console.log("data received",data[1]['name']);
console.log("data received",data);


}).catch(function(error){
console.log("Error in Fetch",error.message);
});


I'm fetching valid JSON data from both URLs, but with slightly different structure

var url1 = 'http://jsonplaceholder.typicode.com/users';
var url2 = 'http://teaconcepts.net/temp/api_test.php';


If I load data from URL1, things are fine. But if I load url2 i get an error "Failed to fetch"

What gives???

See demo: http://jsbin.com/yaxecewopu/1/edit?js,console

Answer

The issue here is the same-origin policy. If you run this JavaScript on http://teaconcepts.net it will work. Or, you can get teaconcepts.net to respond with an Access-Control-Allow-Origin header to allow any origin or specific origins (such as jsbin.com and stackoverflow.com)

Comments