当API不允许Access-Control-Allow-Origin时该怎么办 [英] What to do when an API doesn't allow Access-Control-Allow-Origin
问题描述
我对所有这些同源策略的事情感到疯狂。
I'm driving crazy with all this same-origin-policy thing.
当我尝试向Google Maps API发出请求时,我没有遇到任何问题:
When I try to do a request to the Google Maps API I have no problems:
var jsonData = $.ajax({
url:"http://maps.googleapis.com/maps/api/geocode/json?address=",
dataType:"json",
async:true,
success: function(json){...}
}
我认为这是因为Google Maps API允许Access-Control-Allow-Origin。但是当我尝试使用openls.geog.uni-heidelberg.de API我得到了跨源错误:
I think that is because Google Maps API allow Access-Control-Allow-Origin. But when I try to use the openls.geog.uni-heidelberg.de API I get the cross-origin error:
var xmlData = $.ajax({
type: "GET",
url:"http://openls.geog.uni-heidelberg.de/route?"
//dataType:"jsonp xml",
dataType: "xml",
async:true,
crossDomain : true,
success: function(xml){...}
}
否'Acc ess-Control-Allow-Origin'标头出现在请求的资源上。因此,不允许访问 http:// localhost 。
有人认为我不明白的是,如果openls API不允许跨源,为什么可以直接从我的浏览器直接输入请求,只需输入以下网址:
One think I dont understand is if the openls API doesn't allow cross-origin why can do a request directly from my browser just typing the url like:
但是我不能用jquery来做。我也尝试了jsonp解决方案,但它不能用于xml。
But I can not do it using jquery. I have also tried the jsonp solution but it's not working with xml.
对于发生了什么事情的一些想法?
Some idea of what is going on?
推荐答案
我在本地运行的两个项目(Angular App和Node.JS Webservices)的交互引起的CORS问题上花费了太长时间
i struggled for way too long with CORS issues caused by the interaction of two projects running locally (Angular App and Node.JS Webservices)
看看简单易用的解决方法:Chrome的插件AllowControlAllowOrigin。
Behold the short easy workaround : Chrome's plugin AllowControlAllowOrigin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
只需将单选按钮从红色切换为绿色,不再阻止请求,错误或警告!
我希望它能与你的API一起使用,当然它不是一个永久性的解决方案,但这是避免在那些烦人的经常性问题上浪费时间的好方法。
Just switch the radio button from red to green, and no more blocked request, error or warning ! I hope it'll work with your API, Of course it isn't a permanently solution but that's a great way to avoid loosing time on those anoying recurrent issues.
这篇关于当API不允许Access-Control-Allow-Origin时该怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!