What to do when an API doesn't allow Access-Control-Allow-Origin

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-23 18:56:37

问题


I'm driving crazy with all this same-origin-policy thing.

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){...}
}

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){...}
}

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

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:

http://openls.geog.uni-heidelberg.de/route?start=9.256506,49.240011&end=8.72083,49.7606&via=&lang=de&distunit=KM&routepref=Bicycle&weighting=Shortest&avoidAreas=&useTMC=false&noMotorways=false&noTollways=false&noUnpavedroads=false&noSteps=false&noFerries=false&instructions=false

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?


回答1:


i struggled for way too long with CORS issues caused by the interaction of two projects running locally (Angular App and Node.JS Webservices)

Behold the short easy workaround : Chrome's plugin AllowControlAllowOrigin.

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

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.



来源:https://stackoverflow.com/questions/32946513/what-to-do-when-an-api-doesnt-allow-access-control-allow-origin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!