0

I am trying to conenct to any external server in order to display server time instead of the machine time in JavaScript.

I have tried reading

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags? , Understanding XMLHttpRequest over CORS (responseText) , and How does Access-Control-Allow-Origin header work? but am very limited in knowledge for this subject, so am confused on how to implement the suggestions to get access to a server time.

I am still getting the error:

Access to XMLHttpRequest at 'https://www.stackoverflow.com/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

And don't know how to fix it. This is the current code that I have:

HTML:

<html>

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Server date/time</title>
    <script language="javascript" src="main.js"></script>
  </head>
  <script language="javascript">
  document.write("Server time is: " + date);
  </script>
  <body>
  </body>

JavaScript:

var xmlHttp;
function serverTime(){
    try {
        //FF, Opera, Safari, Chrome
        xmlHttp = new XMLHttpRequest();
    }
    catch (err1) {
        //IE
        try {
            xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch (err2) {
            try {
                xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch (err3) {
                // use CPU time.
                alert("Using CPU Time");
            }
        }
    }
    xmlHttp.open('HEAD',"https://www.stackoverflow.com",false);
    xmlHttp.setRequestHeader("Content-Type", "text/html");
    xmlHttp.send('');
    return xmlHttp.getResponseHeader("Date");
}

var st = serverTime();
var date = new Date(st);

Ideas on what I am doing wrong and what I can do to get the server time? Thanks!

Petlover620
  • 117
  • 6
  • Does this answer your question? [CORS - What is the motivation behind introducing preflight requests?](https://stackoverflow.com/questions/15381105/cors-what-is-the-motivation-behind-introducing-preflight-requests) – Amacado Jul 17 '20 at 21:08
  • @Amacado This helps me understand the reasoning behind CORS, but I am still confused on how I can fix my code to be able to get the server time? – Petlover620 Jul 20 '20 at 21:53
  • 1
    I'm not sure if I got you right, but if you have no control on the remote server (like you mentioned "any server") and the remote server is blocking cors.. You basically can't. – Amacado Jul 21 '20 at 09:09

0 Answers0