【问题标题】:javascript how to get json data with api call to redirected urljavascript如何通过api调用重定向url获取json数据
【发布时间】:2018-06-11 06:39:51
【问题描述】:

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

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

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

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

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

对两个 HTTPS 请求使用 postman,我得到相同的 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

【问题讨论】:

    标签: javascript jquery json .htaccess redirect


    【解决方案1】:

    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>

    【讨论】:

    • 我不能指定类似 ?callback= 的东西吗?而是在我的 https 请求结束时?
    【解决方案2】:

    如果您将$.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);}      
        });   
    });
    

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多