Set and Get Custom Response Header values using Angular 5 and Express.js – Node.JS

May 22, 2019

While working with Node.js and Angular, sometimes you might need to set some custom values in Response Header from the server-side and get these values in your Angular application. These values can be some tokens, keys or anything. This article is about completing this requirement.

Server-side using Express.js and Node.js

To set a custom value in the response header, you have to write the following code in your Express.JS server

Even if you set this token in the response header, to get this in your Angular application you need to allow these header values. The allowed default header values are

Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma

To allow your custom header value, you need to use the Cors module of Node.JS.

To install the Cors module, use the following command.

Now the code to allow the customer header values with Cors module use the following code

Accessing the header values in your Angular 5 application

 

To get the header value in the application, you need to access the whole response object. For this, you need to add on observe: “response”  to the request options in the following way

When subscribing to the observable, you can get the value of the header value using.

This will show the token in the browser console. You can use get the response data from response.body

 

No Comments

Leave a Reply

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