繁体   English   中英

javascript如何使用api调用获取JSON数据以重定向到url

[英]javascript how to get json data with api call to redirected url

我正在从gltich API获取json数据。

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

当我转到该链接时,URL重定向到另一个域

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

(域名从gomix.me更改为glitch.me

对两个HTTP请求使用邮递员 ,我得到相同的JSON数据。 但是,当使用jQuery .getJSON方法时,两者不会产生相同的结果

 $(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> 

是否可以通过将重定向到gomix.me的URL获取JSON数据,或者我只能仅使用最终端点glitch.me

Gomix请求被CORS政策阻止。 您可以使用此heroku应用程序绕过它: 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> 

如果您将$.ajaxdataType: 'jsonp'它将为您提供帮助。

$(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);}      
    });   
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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