title: Access-Control-Allow-Origin issue with CORS and HTTPS redirect (IIS / IISNode / NodeJS)
body: <p>I have a web application that is in two parts:</p>
  
  <ul>
  <li>The "front-end" based in Angular (under Chrome) running on localhost:8000</li>
  <li>The "back-end" based in ExpressJS/NodeJS, running on localhost:3000</li>
  </ul>
  
  <p>In trying to gradually convert the application to entirely use HTTPS, I thought it would be better to convert the back-end, first.  I have built it so that I can toggle the ability to enable/disable HTTPS on the back-end.</p>
  
  <p>I have set up the back-end to run: </p>
  
  <ul>
  <li>With two bindings under IIS: http and https</li>
  <li>The NodeJS application under IISNode.</li>
  </ul>
  
  <p>The problem comes about when I attempt to run the entire application (front- and back-end) under localhost in a local development environment, but with an HTTP-to-HTTPS rewrite (redirect) rule.  After that I receive CORS errors on the front-end.</p>
  
  <p>In short, in my local development environment, I am attempting:</p>
  
  <p><a href="https://i.stack.imgur.com/PkUMZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PkUMZ.png" alt="Basic App"></a></p>
  
  <p>After reading on all things CORS for hours, I adjusted the web.config and the applicationHost.config based upon <a href="https://www.carlosag.net/articles/enable-cors-access-control-allow-origin.cshtml" rel="nofollow noreferrer">this blog post</a> and <a href="https://stackoverflow.com/questions/42031885/cors-in-iis-issue-with-credentials-and-wildcard-in-access-control-allow-origin">this StackOverflow article</a> in an attempt to capture the Request Origin header value.  Here is what they look like.</p>
  
  <p>My <strong>applicationHost.config</strong> contains this section:</p>
  
  <pre><code>&lt;location path="Default Web Site"&gt;
      &lt;system.webServer&gt;
          &lt;rewrite&gt;
              &lt;allowedServerVariables&gt;
                  &lt;add name="CAPTURED_ORIGIN" /&gt;
                  &lt;add name="RESPONSE_Access-Control-Allow-Origin" /&gt;
              &lt;/allowedServerVariables&gt;
          &lt;/rewrite&gt;
      &lt;/system.webServer&gt;
  &lt;/location&gt;
  </code></pre>
  
  <p>And here is my <strong>Web.config</strong>:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;!--
       This configuration file is required if iisnode is used to run node processes behind
       IIS or IIS Express.  For more information, visit:
  
       https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
  --&gt;
  
  &lt;configuration&gt;
    &lt;system.webServer&gt;
      &lt;handlers&gt;
  
        &lt;!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module --&gt;
        &lt;add name="iisnode" path="bin/www" verb="*" modules="iisnode" /&gt;
      &lt;/handlers&gt;   
      &lt;rewrite&gt;
        &lt;rules&gt;
          &lt;rule name="Capture Origin Header"&gt; 
              &lt;match url=".*" /&gt; 
              &lt;conditions&gt; 
                &lt;add input="{HTTP_ORIGIN}" pattern=".+" /&gt; 
              &lt;/conditions&gt; 
              &lt;serverVariables&gt; 
                &lt;set name="CAPTURED_ORIGIN" value="{C:0}" /&gt; 
              &lt;/serverVariables&gt; 
              &lt;action type="None" /&gt; 
          &lt;/rule&gt;
  
          &lt;!-- HTTP-to-HTTPS redirect --&gt;
                  &lt;rule name="Redirect to HTTPS" enabled="true" stopProcessing="true"&gt;
                      &lt;match url="(.*)" ignoreCase="true" /&gt;
              &lt;conditions logicalGrouping="MatchAll" trackAllCaptures="true"&gt;
                          &lt;add input="{HTTPS}" pattern="^off$" /&gt;
                          &lt;add input="{HTTP_HOST}" pattern="([^/:]*?):[^/]*?" /&gt;
              &lt;/conditions&gt;                   
                        &lt;action type="Redirect" url="https://{C:1}:3443/{R:0}" appendQueryString="true" redirectType="Temporary" /&gt;
                  &lt;/rule&gt;
  
          &lt;!-- First we consider whether the incoming URL matches a physical file in the /public folder --&gt;
          &lt;rule name="StaticContent"&gt;
            &lt;action type="Rewrite" url="public{REQUEST_URI}" /&gt;
          &lt;/rule&gt;
  
          &lt;!-- All other URLs are mapped to the node.js site entry point --&gt;
          &lt;rule name="DynamicContent"&gt;
            &lt;conditions&gt;
              &lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True" /&gt;
            &lt;/conditions&gt;
            &lt;action type="Rewrite" url="bin/www" /&gt;
          &lt;/rule&gt;
        &lt;/rules&gt;
        &lt;outboundRules&gt; 
          &lt;rule name="Set-Access-Control-Allow-Origin for known origins"&gt; 
            &lt;match serverVariable="RESPONSE_Access-Control-Allow-Origin" pattern=".+" negate="true" /&gt; 
            &lt;action type="Rewrite" value="{CAPTURED_ORIGIN}" /&gt;
          &lt;/rule&gt; 
        &lt;/outboundRules&gt;       
      &lt;/rewrite&gt;
  
      &lt;!-- Make sure error responses are left untouched --&gt;
      &lt;httpErrors existingResponse="PassThrough" /&gt;
  
    &lt;/system.webServer&gt;
    &lt;appSettings&gt;
      &lt;add key="HTTPS_ENABLED" value="true" /&gt;
    &lt;/appSettings&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <p>The NodeJS application is also set up to handle CORS from localhost:8000, localhost:3000, localhost:3443 (local https), and "null" (converted to a string).  (More on that, later.)</p>
  
  <p>But if I use this configuration, then I get the following error in the front-end:</p>
  
  <blockquote>
    <p>XMLHttpRequest cannot load
    <a href="http://localhost:3000/foo/bar/" rel="nofollow noreferrer">http://localhost:3000/foo/bar/</a>
    Response for preflight is invalid (redirect)</p>
  </blockquote>
  
  <p>I suspect this is because IIS handled the redirect, but as a result it is handling the preflight check (HTTP OPTIONS) with an invalid response (redirect).  However, according to <a href="https://stackoverflow.com/questions/42168773/how-to-resolve-preflight-is-invalid-redirect-in-cors/42172732#42172732">this StackOverflow article</a>, and the answer by <a href="https://stackoverflow.com/users/441757/sideshowbarker">@sideshowbarker</a>, leads me to believe that the current version of Chrome,  59.0.3071.104, should be able to handle the HTTP redirect response from the CORS preflight OPTIONS request.</p>
  
  <p>If I remove the server variables from the applicationHost.config and the HTTP-to-HTTPS rewrite and other rules and from the web.config, and then add code to allow the NodeJS application to handle the redirect to HTTPS, then the revised application looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/KijBk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KijBk.png" alt="Revised App"></a></p>
  
  <p>Then it appears an unknown (NodeJS? IIS?) server error occurs because the request is cancelled: </p>
  
  <p><a href="https://i.stack.imgur.com/TNaSp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TNaSp.png" alt="Chrome Dev Tools Networking 1"></a></p>
  
  <p><a href="https://i.stack.imgur.com/5YBej.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5YBej.png" alt="Chrome Dev Tools Networking 2"></a></p>
  
  <p>You can see the cancellation in chrome://net-internals/#events even though the Origin in the request and the Access-Control-Allow-Origin in the response headers match:</p>
  
  <p><a href="https://i.stack.imgur.com/FRnkz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FRnkz.png" alt="Chrome net-internals"></a></p>
  
  <p>There is no useful error message (even though one is being received by the client) which leads me to believe that it is IIS and not NodeJS that is cancelling the request and sending back no useful information.</p>
  
  <p>I ended up adding a "null" entry to handle CORS when running under the NodeJS Lite Server (and not IIS as an experiment), but I need this to run under IIS/IISNode.  However, there seems to be a problem with then IIS / IISNode / NodeJS combination.</p>
  
  <p>I suspect that the Request Origin of "null" is most likely the result of a request, where the server performs a redirect, because you really have two requests:
  - The original request from the browser
  - The request that is the result of the redirect
  When the redirect occurs, I am hypothesizing that the origin in the redirected request is not that same as the original URL, and for the reasons stated in <a href="https://www.w3.org/TR/cors/#generic-cross-origin-request-algorithms" rel="nofollow noreferrer">https://www.w3.org/TR/cors/#generic-cross-origin-request-algorithms</a>, the Origin request header within the redirect is null.</p>
  
  <p>However, that doesn't explain, why, when I let NodeJS handle the redirect that the Origin request and the Access-Control-Allow-Origin response header values are both null and the request still gets cancelled.  :-/</p>
  
  <p>Finally, if I eliminate any attempt at HTTP-to-HTTPS redirect, then the application works without issue in my development environment.</p>