2017-06-24 37 views
0

我試圖從不允許CORS的域中檢索json,並且我無法訪問服務器以允許它。作爲一個例子,我用googleapis替換了url。YQL提取返回空對象

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

但是響應警報(從而返回)獲取是空的。

enter image description here

請指引我在正確的方向。謝謝。

P.S.我不想使用jQuery,更喜歡JavaScript。

回答

1

A fetch(…)調用返回包含響應對象的承諾,並從中獲取JSON,您需要使用.json()方法,該方法返回包含JSON的承諾。

所以一起看序列化JSON數據,你需要做的是這樣的:

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