2017-05-06 37 views
4

我使用獲取API從其他API的數據,這是我的代碼:提取錯誤否「訪問控制允許來源」標頭出現在所請求的資源

var result = fetch(ip, { 
     method: 'get', 
    }).then(response => response.json()) 
     .then(data => { 
     country = data.country_name; 
     let lat = data.latitude; 
     let lon = data.longitude;      
     //fetch weather api with the user country 
     return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`); 
    }) 
    .then(response => response.json()) 
    .then(data => { 
     // access the data of the weather api 
     console.log(JSON.stringify(data)) 
    }) 
    .catch(error => console.log('Request failed', error)); 

,但我面對錯誤在控制檯:

Fetch API cannot load https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/52.3824,4.8995. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 

我設置頭第二抓取:

return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`, { 
    mode: 'no-cors', 
    header: { 
    'Access-Control-Allow-Origin':'*', 
    } 
}); 

錯誤會消失,但console.log(JSON.stringify(data))做不在控制檯中記錄任何內容,並且提取不會返回任何值。 我的代碼有什麼問題?

+0

http://stackoverflow.com/q/20035101/2037335 – Jude

回答

3

問題不在於你的JavaScript代碼,它是在API中,服務器不支持跨源請求,如果你是這個API的所有者,你必須添加'Access-Control-Allow-Origin '標題與允許的來源(*允許從任何來源)的迴應。 在某些情況下jsonp請求可能有效。

注意:只有當請求從瀏覽器生成時纔會發生此問題

相關問題