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. 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, 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 you might want to check one some of my other posts on express.js if interested.