Failed to execute 'send' on 'XMLHttpRe

2019-01-29 05:58发布

问题:

I'm trying to connect to google with a simple get request through JS and it seems to always be giving me the same error.

"Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://google.com'."

Any clue why this would be happening? Relevant code is below.

        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", "http://google.com", false);
        try {
            xmlHttp.send();
        } catch (err) {
            alert("EXCEPTION: " + err.message);
        }
        alert("here's the result of the get: " + xmlHttp.responseText);

回答1:

This is simply a cross-origin permission failure, due to the same origin policy. If you ran this same request asynchronously and looked in your console, you'd see the much more helpful error message:

XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[whatever]' is therefore not allowed access.

This is because only scripts run on pages from http://www.google.com may read resources from http://www.google.com. If the resource being fetched served appropriate CORS headers (e.g., Access-Control-Allow-Origin), you would not see this error. (However, http://www.google.com serves no such headers).