0

This is not a duplicate of "How does Access-Control-Allow-Origin header work?".

I read some Q&A like "How to send GET request in JavaScript?" but the answers do not work (for example, this).

The error is as follows:

Access to XMLHttpRequest at 'https://~' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Could you give me an example of working code?

I want to get the html of the target URL.

my code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <script>
            var theUrl = "https://www.google.com";

            function httpGetAsync(theUrl, callback)
            {
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.onreadystatechange = function() { 
                    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                        callback(xmlHttp.responseText);
                }
                xmlHttp.open("GET", theUrl, true); // true for asynchronous 
                xmlHttp.send(null);
            }

            function callback(text){
                console.log(text);
            }

            httpGetAsync(theUrl, callback);
        </script>
    </body>
</html>
  • You should post your code (specifically the request which causes the error). – dunli Mar 13 '20 at 02:45
  • If you're retrieving info from your server, enable the header on your server. If it's not your server, you won't be able to connect to it directly; bounce the request off your server instead so CORS restrictions don't cause problems. – CertainPerformance Mar 13 '20 at 02:46
  • I want a working code. The answer of the question "How does Access-Control-Allow-Origin header work?" does not contain a JavaScript working example. –  Mar 13 '20 at 02:53
  • @dunli I posted the code. Do you post an answer? –  Mar 13 '20 at 03:03
  • I wonder why there is no working code of this simple basic task on the internet. –  Mar 13 '20 at 03:05

0 Answers0