【问题标题】:YQL fetch returns empty objectYQL fetch 返回空对象
【发布时间】:2017-11-27 20:03:35
【问题描述】:

我正在尝试从不允许 CORS 的域中检索 json,并且我无权访问服务器以允许它。我在这里用googleapis 替换了网址作为示例。

  const url = 'https://www.googleapis.com/storage/v1/b/example-bucket/o/foo%2f%3fbar';
  const yUrl = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json';

  fetch(yUrl)
        .then(function(response){
        alert(JSON.stringify(response, null, 4));
    })

如果我们在浏览器本身中打开 yUrl,它可以正常工作:http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22https%3A%2F%2Fwww.googleapis.com%2Fstorage%2Fv1%2Fb%2Fexample-bucket%2Fo%2Ffoo%252f%253fbar%22&format=json

但是,警告(并因此返回)获取的响应是空的。

请引导我正确的方向。谢谢。

附:我不想使用 jQuery,更喜欢 JavaScript。

【问题讨论】:

    标签: javascript cors fetch-api yql


    【解决方案1】:

    fetch(…) 调用返回一个包含响应对象的 Promise,要从中获取 JSON,您需要使用 .json() 方法,该方法返回一个包含 JSON 的 Promise。

    所以要一起查看序列化的 JSON 数据,你需要做这样的事情:

    fetch(yUrl)
        .then(response => response.json())
        .then(json => JSON.stringify(json))
        .then(function(json) {
            alert(json);
        })
    

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      相关资源
      最近更新 更多