When receiving an http request from a client, that request will contain all kinds of headers that tell the server useful information about the request. The subject of headers in general can eat up a lot of time because there are a lot of them. However there are great resources such as at Mozilla as usual that outline what all the typical standard headers are when it comes to http requests. This is however a post on expressjs a tired yet true nodejs framework and how to work with incoming request headers.
So then in this post I will be quickly covering some examples of how to work with request headers in express.js with some help with the req.get method method, and the req.headers array that can be found in a request object.
Request headers depend on the method of the request such as GET, and POST. A POST request header for example will contain a content-type header to tell the server the type of content that it is being given in the body of the request. However a GET request would not contain such a header, because it is just simply requesting whatever there is at a given location. Also It goes without saying that response headers differ slightly from request headers.
There is the req.get method that can be used to get a header to which you know the name off. If you do not know the name there is also the req.headers array that will store everything of interest when it comes to the request headers.
Here is an example of a router that can be added into a express.js demo with app.use, say you save it in a folder at \/routes\/headers.js:
And then use it in a main app.js file like this:
If you then start app.js in the command line with node and go to localhost:8080/headers in the browser you might see something like this.
I am sorry this is a thin post, I might expand on it more as my collection of content, and demos on express.js grows. In the mean time there is taking the time to look into what all the standard headers are and what they do. Some headers are obvious such as the user agent header that is used to inform a server what kind of client system is being use. So then this information can then be used to redirect a visitor to a download page for a binary that will work for there operating system for example.