Tuesday , 16 July 2019
Home / Programming / JavaScript / HTTP Headers – Advanced JavaScript Tutorial

HTTP Headers – Advanced JavaScript Tutorial

HTTP headers are just pieces of information of the request and response. Browsers will automatically send this kind of information by default. Sometimes you’ll want to modify these HTTP headers so you can let servers know what to expect. Servers also send you back HTTP headers which allow you to know more information about the response itself.

Sending Custom Headers

We’ll be working with the same script we had in the last tutorial. Like last time, you must test this on a live or local sever. Update your script to this.

I only added 1 line of code into this. Let’s focus on the setRequestHeader() method. This method has 2 parameters. The name of our header and it’s value. You can give this header any name you want and any value you want. Of course, you can also modify the current headers already set by your browser. Let’s change that one line to this.

The Content-Type is a header already defined for you, but you can alter it if you wish. Be warned though, most browsers will prevent you from modifying certain headers as it can lead to risky behavior.  One last thing, the setRequesetHeader() method should be used ONLY after the open() method, but before the send() method.

Getting Headers

As mentioned before, servers will also send back headers with their response. There are 2 methods for grabbing these headers. Let’s update our if statement in our event to this.

We are using a method called getAllResponseHeaders(). This method will return all the  headers sent by the server in one long string. Of course, you can get 1 specific header. To do this, update that line of code to this.

The getResponseHeader() method will grab 1 specific header from the response. The header that is returned depends on the name you pass into this method. In our case, we want to grab the Date header.


You should be careful when working with HTTP headers. They can affect the response and requests you make. For a list of all possible headers and their values, then go here.


About Jasko Koyn

Check Also

Video Events

Video Events – Advanced JavaScript Tutorial

Video events allow you to tap into what’s currently happening with the video. There are …

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.