简体   繁体   中英

Google Cross-Origin Request

I am trying to use Google JS API from my HTML page and I have to do something like:

<script src="https://www.google.com/jsapi?key=MY_API_KEY"/>

But I am getting the following error:

Firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/jsapi?key=MY_API_KEY . (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Chrome:

XMLHttpRequest cannot load https://www.google.com/jsapi?key=MY_API_KEY . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:8080 ' is therefore not allowed access. The response had HTTP status code 405.

As I have read it is caused by browsers restrictions to crossed request but I have no clue about how to fix it so I can do that request. Can anyone give me a tip?

I fixed it changing the way I made the request:

<script>
    $.ajax({
        url: "https://www.google.com/jsapi?key=MY_API_KEY",
        crossDomain: true,
        method: 'GET',
        async: false,
        dataType: 'script',
        headers:{
            "X-Requested-With":"XMLHttpRequest"
        }
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM