title: How to Connect to a Time Server JavaScript
body: <p>I am trying to conenct to any external server in order to display server time instead of the machine time in JavaScript.</p>
  <p>I have tried reading</p>
  <p><a href="https://stackoverflow.com/questions/7015782/how-do-i-use-access-control-allow-origin-does-it-just-go-in-between-the-html-he">How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?</a>
  , <a href="https://stackoverflow.com/questions/13400594/understanding-xmlhttprequest-over-cors-responsetext/13400954#13400954">Understanding XMLHttpRequest over CORS (responseText)</a>
  , and <a href="https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work">How does Access-Control-Allow-Origin header work?</a>
  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.</p>
  <p>I am still getting the error:</p>
  <pre><code>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.
  </code></pre>
  <p>And don't know how to fix it. This is the current code that I have:</p>
  <p>HTML:</p>
  <pre><code>&lt;html&gt;
  
    &lt;head&gt;
      &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
      &lt;title&gt;Server date/time&lt;/title&gt;
      &lt;script language=&quot;javascript&quot; src=&quot;main.js&quot;&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;script language=&quot;javascript&quot;&gt;
    document.write(&quot;Server time is: &quot; + date);
    &lt;/script&gt;
    &lt;body&gt;
    &lt;/body&gt;
  </code></pre>
  <p>JavaScript:</p>
  <pre><code>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(&quot;Using CPU Time&quot;);
              }
          }
      }
      xmlHttp.open('HEAD',&quot;https://www.stackoverflow.com&quot;,false);
      xmlHttp.setRequestHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);
      xmlHttp.send('');
      return xmlHttp.getResponseHeader(&quot;Date&quot;);
  }
  
  var st = serverTime();
  var date = new Date(st);
  </code></pre>
  <p>Ideas on what I am doing wrong and what I can do to get the server time? Thanks!</p>