Null Response Headers


Background
HTTP Request and Response Header are very cool components of the web. They allow for transmission of some intricate information concerning how the a particular request should be handled. Sometimes however, developers "abuse" the system and hijack this feature for transmitting small amounts of data to and from the webserver. I am one of these system abusers, lol. It just happens that sometimes, our software solutions give us little choice than to do some awkward things. Before you start castigating yourself, its not really a bad practice, so far you only send little amount of text data.

Issue
Most of my web apps now run on Javascript front-ends, and this comes with its own challenges. I developed a software that sends data to the server to generate a PDF file and the server responds with the filename of the file generated for the client to download. As you could rightly guess, things worked quite perfectly until I migrated to production. The frontend now resided on a separate domain. Each time I queried for the content of my custom header using request.getResponseHeader in Javascript, I got null. See my code sample below:


$.ajax({type: "POST", url: 'http://myappurl.com', headers: { "custom-header": 'my custom header' },
            data: JSON.stringify({}),
            success: function (response, status, request) {
                    var filename = request.getResponseHeader('filename');
      alert(filename); // I GOT NULL HERE
                }
            }, error: function () {
                alert('an error occurred');
            }
        });


Solution
It happens that although headers may be present, in cross domain situations, the headers are not made accessible to the client. Adding "Access-Control-Expose-Headers" to the web config resolves this in ASP.NET. "Access-Control-Expose-Headers" ensures that some specific headers are accessible by the client in cross domain situations. See sample below:


<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Cache-Control, filename,  Accept" />
 <add name="Access-Control-Expose-Headers" value="filename" />
      </customHeaders>
    </httpProtocol>
...
<system.webServer>

Comments

Popular posts from this blog

Resize or Crop Image before Upload Using HTML5 File API

Exception from HRESULT: 0x80131040

Get Creative With Data Tables: Row Click Events