获取错误请求的资源上不存在 'Access-Control-Allow-Origin' header
fetch error No 'Access-Control-Allow-Origin' header is present on the requested resource
我正在使用 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));
但我在控制台中遇到错误:
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.
我为第二次获取设置了 headers:
return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`, {
mode: 'no-cors',
header: {
'Access-Control-Allow-Origin':'*',
}
});
错误将消失,但 console.log(JSON.stringify(data))
不会在控制台中记录任何内容,并且提取不会 return 任何值。
我的代码有什么问题?
问题不在您的 JavaScript 代码中,而是在 API 中,如果您是此 API 的所有者,服务器不支持跨源请求您必须将 'Access-Control-Allow-Origin' header 添加到具有允许来源的响应中(* 允许来自任何来源)。
在某些情况下 jsonp 请求可能有效。
注意:只有在浏览器生成请求时才会出现此问题
在 url
之后使用“no-cors”参数时不会出现此问题
fetch(url, {mode: "no-cors"})
我正在使用 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));
但我在控制台中遇到错误:
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.
我为第二次获取设置了 headers:
return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`, {
mode: 'no-cors',
header: {
'Access-Control-Allow-Origin':'*',
}
});
错误将消失,但 console.log(JSON.stringify(data))
不会在控制台中记录任何内容,并且提取不会 return 任何值。
我的代码有什么问题?
问题不在您的 JavaScript 代码中,而是在 API 中,如果您是此 API 的所有者,服务器不支持跨源请求您必须将 'Access-Control-Allow-Origin' header 添加到具有允许来源的响应中(* 允许来自任何来源)。 在某些情况下 jsonp 请求可能有效。
注意:只有在浏览器生成请求时才会出现此问题
在 url
之后使用“no-cors”参数时不会出现此问题fetch(url, {mode: "no-cors"})