我要使用JSONP。
在编写这样的代码时遇到了此错误:
所请求的资源上没有“ Access-Control-Allow-Origin”标头。 因此,不允许访问来源“ http://localhost”。
出什么问题了?
function getAirLine(from , to , date) {
var href = "https://api.flightstats.com/flex/schedules/rest/v1/json/from/"+from+"/to/"+to+"/departing/"+date+"?appId=[myKey1]&appKey=[myKey2]&extendedOptions=languageCode:ko";
$.ajax({
url : href,
dataType: 'jsonp',
success : function(datas) {
console.log(datas);
var dataSet = [];
for (var i = 0; i < datas.scheduledFlights.length; i++) {
for(var j = 0 ; j < datas.appendix.airlines.length ; j++){
if(datas.scheduledFlights[i].carrierFsCode == datas.appendix.airlines[j].fs){
airlines = datas.appendix.airlines[j].name;
}
}
var dataArr = [];
dataArr.push(datas.scheduledFlights[i].departureAirportFsCode);
dataArr.push(datas.scheduledFlights[i].departureTime.substring(11,16))
dataArr.push(datas.scheduledFlights[i].arrivalAirportFsCode)
dataArr.push(datas.scheduledFlights[i].arrivalTime.substring(11,16))
dataArr.push(datas.scheduledFlights[i].carrierFsCode + datas.scheduledFlights[i].flightNumber)
dataArr.push(airlines);
dataSet.push(dataArr);
}
console.log(dataSet);
$('#realTime').DataTable({
destroy: true,
data: dataSet,
columns: [
{ title: "From" },
{ title: "Depart.Time" },
{ title: "To" },
{ title: "Arrial.Time" },
{ title: "AirLine" },
{ title: "AirCode" }
]
});
},
error: function(datas) {
console.log('실패 - ', datas);
}
});
}
我们应该如何解决呢?
答案 0 :(得分:0)
您必须以某些语言(例如PHP,JAVA,C#等)在标头中启用CORS php中的示例
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
header('Access-Control-Allow-Methods: GET, POST, PUT');
或仅用于JS。 Idk如何工作,但:D 它是https://cors-anywhere.herokuapp.com/的一种方法 例子
const CORS = "https://cors-anywhere.herokuapp.com/";
const endpoint = CORS + "https://api.deezer.com/playlist/3314523926/tracks";
我在codepen https://codepen.io/rogergcc/pen/wyggGX
中有一个例子