FirstOfMany FirstOfMany - 1 year ago 97
AngularJS Question

Send JWT from AngularJS to Node.js

An AngularJS app needs to exchange a JWT with the Node.js instance that serves it. The Node.js instance has a

route which returns a JWT to the Angular client. What specific changes need to be made to the code below so that 1.) The AngularJS app can send the JWT back to the Node.js instance's
route, and 2.) the Node.js code can isolate the JWT as a variable for processing?

The current AngularJS code for calling the backend
route is:

$http.get('user').then(function(response) {
console.log('response is: ');
if ( === 'anonymous') {
$rootScope.authenticated = false;
} else {
$rootScope.userJWT =;
var payload = $rootScope.userJWT.split('.')[1];
payload = $window.atob(payload);
payload = JSON.parse(payload); =;
self.authorities = payload.authorities;
$rootScope.authenticated = true;
}, function() {
$rootScope.authenticated = false;

And the Node.js code for the backend
route is:

app.get('/user**', function(req, res) {
console.log("You Hit The User Route TOP");
//How do we get the JWT from req?
var user = getUserName(theJwt);
var token = getToken(user);
var jwtJSON = getUser(token);
if( (jwtJSON["token"] == 'error') || jwtJSON["token"] == 'anonymous' ) {
res.sendStatus(500); // Return back that an error occurred
} else {
console.log("You Hit The User Route BOTTOM");

Note, the Node.js instance includes
var jwt = require('jsonwebtoken');
, and one of the processing methods will decode the JWT using
var decoded = jwt.decode(token, {complete: true});
, as per the

Answer Source

When using JWT there is no required way to communicate the token.

The most common way is to place the token into an HTTP Header.

On the AngularJS side you would make an HTTP request with an extra header (e.g. X-Auth-Token) which contains the JWT.

Example of AngularJS side:

var config = {
    headers: {
        "X-Auth-Token": $rootScope.userJWT
$http.get('routeThatNeedsJWT', config).then(function(response) { ... });

On the Node.js side you would get the contents of the header and process it using the jsonwebtoken library.

Example of Node.js side:

app.get('/routeThatNeedsJWT', function(req, res) {
    var rawTokenFromHeader = req.get('X-Auth-Token'); // Get JWT from header
    try {
        var jwtJSON = jwt.verify(token, 'secret'); // Verify and decode JWT
    } catch (err) {
        res.sendStatus(500);  // Return back that an error occurred

Helpful links:

Express 4.x getting header value

jsonwebtoken library verify token