javascript - CORS 策略已阻止从源“null”访问 XMLHttpRequest:
问题描述
我正在根据从heremaps api获得的数据从darksky api请求数据,特别是我正在尝试获取一个地方的地理坐标并从darksky获取天气。
const getWeather = (longi, latit) => {
return new Promise((resolve, reject) => {
console.log("ia m in hello world");
const wetherHttpRequest = new XMLHttpRequest();
wetherHttpRequest.addEventListener("readystatechange", e => {
//console.log(e.target);
if (e.target.readyState === 4 && e.target.status === 200) {
const data = JSON.parse(e.target.responseText);
console.log("data resolved");
resolve(data);
} else if (e.target.readyState === 4) {
console.log("data rejected");
reject("error occured in getting weather");
}
});
wetherHttpRequest.open(
"GET",
`https://api.darksky.net/forecast/8f03e2f020819a37720/${longi},${latit}`
);
wetherHttpRequest.setRequestHeader("Access-Control-Allow-Methods", "GET");
wetherHttpRequest.setRequestHeader("Access-Control-Allow-Headers", "*");
wetherHttpRequest.send();
});
};
这里两个参数 longi 和 latit 是来自 geo-coodinates 承诺的已解决承诺
getGeoLoc().then(
a => {
const datain = a.Response.View[0].Result[0].Location.DisplayPosition;
console.log(datain.Latitude);
console.log(datain.Longitude);
document.getElementById("out1").innerHTML = datain.Longitude;
document.querySelector(".out2").innerHTML = datain.Latitude;
getWeather(datain.Longitude, datain.Latitude).then(
a => {
console.log(a);
},
b => {
console.log(b);
}
);
}
);
我正进入(状态
Access to XMLHttpRequest at 'https://api.darksky.net/forecast/8f03e2f020b9a37720/79.84556,6.93195' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决方案
推荐阅读
- javascript - 在选择更改事件上反应提交表单
- azure-cosmosdb - 如何在 TinkerPop3 中组合选择节点?
- sql - 在 SQL 中生成 Pivot(按小时划分的每个部门的销售额)
- linux - 检索“ls -la”的符号链接和目标链接
- c# - iText 7 - 居中对齐文本和段落
- javascript - 如何在Angular 6中为反应形式设置日期默认值?
- python - 如何从 Excel 或 .csv 文件中读取带有一个标题的两列?
- docker - 将参数传递给 build.gradle
- java - 如何在 Windows 7 中为 JDK 11 设置 java home?
- python - 处理意外关闭python