In this article let us see how to send and receive headers using node js express.

Express Service – Get Request Headers

<requestObject>.headers returns a JavaScript object that consists of all the headers came as part of the request. Since it is a JavaScript object, the header name can be accessed like a property of the object. Let us assume we are making a call to express GET service with a header named “first_name” and its value is “HelloWorld”. Now, consider the below example to see how we can use the <requestObject>.headers to access header values.

var express = require("express");
var app = express();
app.get('/hello',function(req,res){
	//Prints all the headers and its value as JavaScript object.
	console.log(req.headers);
	//Print the value of header 'first_name'.
	console.log(req.headers.first_name);
	res.send();
});
app.listen(8080);

Run the above code and make a call to the service along with header. In this example, we are using postman in the below image to test the service.

express-postman-service

We can also use the header() function in request object to access any specific header.

console.log(req.header("first_name"));

Express Service – Set Response Headers

Use function <responseObject>.header(“Key”,”Value”) to set a header. The below example sets a header “first_name” to the response with value “HelloWorld”.

app.get('/hello',function(req,res){
	res.header('first_name','HelloWorld');
	res.send();
});
Express Get & Set Headers