简体   繁体   中英

javascript how to get json data with api call to redirected url

I'm fetching json data from gltich API.

https://wind-bow.gomix.me/twitch-api/users/freecodecamp

When I go to that link, the url redirects to another domain

https://wind-bow.glitch.me/twitch-api/users/freecodecamp

(domain name change from gomix.me to glitch.me )

Using postman for both HTTPs request, I get the same JSON data. However, both don't produce the same results when using jQuery .getJSON method

 $(document).ready(function() { $.getJSON("https://wind-bow.gomix.me/twitch-api/users/freecodecamp", function(data1) { console.log("Gomix.me URL", data1); // nothing outputted }); $.getJSON("https://wind-bow.glitch.me/twitch-api/users/freecodecamp", function(data2) { console.log("Glitch.me URL", data2); // expected data outputted }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Is it possible to get JSON data through a URL that will be redirected gomix.me , or am I only able to use the final endpoint only glitch.me ?

Gomix request is blocked by CORS policy. You can use this heroku app to bypass it: https://cors-anywhere.herokuapp.com/ .

 $(document).ready(function() { $.getJSON("https://cors-anywhere.herokuapp.com/https://wind-bow.gomix.me/twitch-api/users/freecodecamp", function(data1) { console.log("Gomix.me URL", data1); // now it works }); $.getJSON("https://wind-bow.glitch.me/twitch-api/users/freecodecamp", function(data2) { console.log("Glitch.me URL", data2); // expected data outputted }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

If you use $.ajax with dataType: 'jsonp' it helps you.

$(document).ready(function() {         
    $.ajax({
    url: "https://wind-bow.gomix.me/twitch-api/users/freecodecamp",   
    type: 'GET',   
    dataType: 'jsonp',
    success: function(data1) { console.log("Gomix.me URL", data1);}      
    });   
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM