首页 > 解决方案 > Cross-Origin blocking AJAX connection with Google Maps even with the headers seted

问题描述

Well, I have a SSL domain calling for the Google Maps API.

function typed_address(str) {

            var url = 'https://maps.google.com/maps/api/geocode/json?address='+str;
            var xhttp = new XMLHttpRequest();           
            xhttp.open('GET', url, false);
            xhttp.setRequestHeader('Access-Control-Allow-Origin','*');
            xhttp.setRequestHeader('Access-Control-Allow-Credentials', 'true');
            xhttp.setRequestHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
            xhttp.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
            xhttp.onreadystatechange = function() {
                 if (this.readyState == 4 && this.status == 200) {
                    var result = JSON.parse(this.response);
                    if (result.results[0]) {
                        latlng = result.results[0].geometry.location;
                        document.cookie = 'lat=' + latlng.lat;
                        document.cookie = 'lng=' + latlng.lng;
                        map.setCenter(latlng);
                        marker.setPosition(latlng);
                    }
                 }
            };  
            xhttp.send();
        }

When I do this request within my SSL domain, I have this on my browser console:

Blocked cross-origin request: Same Origin Policy prevents the remote resource from reading at https://maps.google.com/maps/api/geocode/json?address=R.%20PROF.%20LOURIVAL 20% 20% 20% 20% 20% 20% 20% 20PE% 2055016-445. (Reason: 'access-control-allow-credentials' symbol missing in CORS 'Access-Control-Allow-Headers' header during CORS pre-connection
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://maps.google.com/maps/api/geocode/json?address=R.%20PROF.%20LOURIVAL%20VILANOVA%20-%20UNIVERSIT % 20% 20%, 20% 20% 20%, 2055016-445. (Reason: CORS request did not succeed).
NetworkError: A network error occurred.

And here below is what I get on Network debug:

Network browser console

Does anybody know what I'm doing wrong? It seems that it's not reading my request headers...

标签: javascriptajaxgoogle-mapscors

解决方案


当网页输出到浏览器时,您需要指定标题。不在ajax请求中。如果您使用 php,您可以添加 sheaders

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");

要在 Ruby 中设置标题,请参阅这篇文章


推荐阅读