Mi *_* La 8 javascript fetch fetch-api
我正在使用fetch 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));
Run Code Online (Sandbox Code Playgroud)
但我在控制台中遇到错误:
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.
Run Code Online (Sandbox Code Playgroud)
我为第二次获取设置了标题:
return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`, {
mode: 'no-cors',
header: {
'Access-Control-Allow-Origin':'*',
}
});
Run Code Online (Sandbox Code Playgroud)
错误将消失,但console.log(JSON.stringify(data))不在控制台中记录任何内容,并且提取不返回任何值.我的代码有什么问题?
问题不在您的JavaScript代码中,而是在API中,服务器不支持跨源请求,如果您是此API的所有者,则必须在响应中添加"Access-Control-Allow-Origin"标头允许来源(*允许来自任何来源).在某些情况下,jsonp请求可能会起作用.
注意:仅当从浏览器生成请求时才会出现此问题
该问题可以通过在 url 后使用“no-cors”参数来解决
fetch(url, {mode: "no-cors"})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13407 次 |
| 最近记录: |