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))
做不在控制檯中記錄任何內容,並且提取不會返回任何值。 我的代碼有什麼問題?
http://stackoverflow.com/q/20035101/2037335 – Jude