Javascript: XMLHttpRequest problem with Cross-Origin Resource Sharing

浪子不回头ぞ 提交于 2019-12-11 08:09:33

问题


I'm making a JSON request to the Google Places API with:

    function load(){

    var req = new XMLHttpRequest();

    req.open('GET', 'https://maps.googleapis.com/maps/api/place/details/json?reference=CnRhAAAARMUGgu2CeASdhvnbS40Y5y5wwMIqXKfL-n90TSsPvtkdYinuMQfA2gZTjFGuQ85AMx8HTV7axABS7XQgFKyzudGd7JgAeY0iFAUsG5Up64R5LviFkKMMAc2yhrZ1lTh9GqcYCOhfk2b7k8RPGAaPxBIQDRhqoKjsWjPJhSb_6u2tIxoUsGJsEjYhdRiKIo6eow2CQFw5W58&sensor=true&key=xxxxxxxxxxxxx', false);

    req.send(null);

    if(req.status == 200){  

      dump(req.responseText);

        }
}

But Chrome is returning the error:

XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/place/details/json?reference=CnRhAAAARMUGgu2CeASdhvnbS40Y5y5wwMIqXKfL-n90TSsPvtkdYinuMQfA2gZTjFGuQ85AMx8HTV7axABS7XQgFKyzudGd7JgAeY0iFAUsG5Up64R5LviFkKMMAc2yhrZ1lTh9GqcYCOhfk2b7k8RPGAaPxBIQDRhqoKjsWjPJhSb_6u2tIxoUsGJsEjYhdRiKIo6eow2CQFw5W58&sensor=true&key=xxxxxxxxxxxxxx. 
Origin http://sandrayoon.com is not allowed by Access-Control-Allow-Origin.

Is there a way to prevent or circumvent cross-origin resource sharing? I am not very familiar with this security issue.


回答1:


Server should response with "Access-Control-Allow-Origin" header in order to let the browser to pass this response to javascript. You can also set "*" to allow any cross-domain requests.

Here is a good intro to the subject.




回答2:


The only way to prevent this is to send proper Access-Control-Allow-Origin header from the server, which isn't under your control. So the basic answer is no. However you can consider using a server proxy, which would grab data from the server and send it to you from the same host as your client script was served.



来源:https://stackoverflow.com/questions/6845265/javascript-xmlhttprequest-problem-with-cross-origin-resource-sharing

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