title: Why authorization header returns undefined in each request in MEAN application
body: <p>I implemented authentication using JWT. In each request I would like access Authorization token but when I tried to access it always returns undefined.</p>
  
  <p>My Scenario is that I stored authentication token stored in local storage and when authorization token is available it consider authenticated user and allow to access URL and when token is not available.</p>
  
  <p>So I used angular interceptor to add Authorization header in each request. It does add in every request but I am not able to get from server side. In each request I pass Authorization header but it returns always undefined as output.</p>
  
  <p>Please review my code and provide me guidelines.</p>
  
  <blockquote>
    <p>app.route.js [AngularJS]</p>
  </blockquote>
  
  <pre><code>(function () {
  
      function authInterceptor($window) {
          return{
              request: function (config) {
                  if ($window.localStorage['hz-token']) {
                      config.headers.Authorization = 'Bearer ' + $window.localStorage['hz-token'];
                  }
                  return config;
              }
          }
      }
  
      /*
       * Default Route of application
       * @param {$stateProvider} Object
       * @param {$routeProvider} Object
       * @return
       */
  
      function config($stateProvider, $urlRouterProvider, $httpProvider) {
          $urlRouterProvider.otherwise('index');
          $httpProvider.interceptors.push('authInterceptor');
          $stateProvider
                  .state('app', {
                      url: '/',
                      views: {
                          'globalHeaderLine1': {templateUrl: '/partials/headerLine1.html', controller: 'SigninCtrl', controllerAs: 'Signin'},
                          'globalHeaderLine2': {templateUrl: '/partials/headerLine2.html'},
                          'footer': {templateUrl: '/partials/footer.html'}
                      }
                  })
                  .state('app.index', {
                      url: 'index',
                      views: {
                          'globalHeaderLine3@': {templateUrl: '/partials/headerLine3.html'},
                          'globalHeaderLine4@': {templateUrl: '/partials/headerLine4.html'},
                          'globalHeaderLine5@': {templateUrl: '/partials/headerLine5.html'},
                          'globalHeaderLine6@': {templateUrl: '/partials/headerLine6.html'},
                          'globalHeaderLine7@': {templateUrl: '/partials/headerLine7.html'},
                          'content@': {templateUrl: '/views/home/home.html', controller: 'HomeCtrl', controllerAs: 'Home'}
                      }
                  })
                  .state("app.resetpassword", {
                      url: "resetpassword",
                      views: {
                          'content@': {templateUrl: '/views/auth/resetpassword.html', controller: 'ResetPasswordCtrl', controllerAs: 'ResetPassword'}
                      }
                  })
                  .state('app.contactus', {
                      url: 'contactus',
                      views: {
                          'content@': {templateUrl: '/views/home/contactus.html', controller: 'ContactusCtrl', controllerAs: 'Contactus'}
                      }
                  })
                  .state('app.useractivation', {
                      url: 'useractivation',
                      views: {
                          'content@': {templateUrl: '/views/auth/useractivation.html', controller: 'UserActivationCtrl', controllerAs: 'UserActivation'}
                      }
                  })
      }
  
      angular
              .module('AppAquireConsole')
              .factory('authInterceptor', ['$window', authInterceptor])
              .config(['$stateProvider', '$urlRouterProvider', '$httpProvider', config])
              .run(function ($rootScope, $http, notifications, $location, UserService) {
                  if ($location.path() === '/resetpassword' &amp;&amp; ('' !== $location.search().q)) {
                      $http({
                          method: "GET",
                          url: '/api/user/resetPassword?forgotPasswordToken=' + $location.search().q
                      }).success(function (data) {
                          if (data.status === 0) {
                              $location.path("#/");
                              notifications.showSuccess({
                                  message: 'This token has been expired',
                                  hideDelay: 3000, //miliseconds
                                  hide: true // boolean
                              });
                          }
                      });
                  }
              });
  }());
  </code></pre>
  
  <blockquote>
    <p>SignoutCtrl.js [AngulrJS]</p>
  </blockquote>
  
  <pre><code>(function () {
      'use strict'
       function SignoutCtrl($scope, $location, $window, $rootScope, UserService) {
          $scope.isAuth = UserService.isLoggedIn();
          $scope.doLogout = function () {
              //JSON.parse(localStorage.getItem("CurrentUserData"));
              //localStorage.removeItem("CurrentUserData");
              UserService.logOut();
              $rootScope.$broadcast('unauthorized');
              $window.location.reload();
          }
      }
  
      angular
              .module('AppAquireConsole')
              .controller('SignoutCtrl', ['$scope', '$location', '$window', '$rootScope', 'UserService', SignoutCtrl]);
  }());
  </code></pre>
  
  <blockquote>
    <p>Config.js : I defined allow access Authoraization in nodejs but why don't return header value that I don't know.</p>
  </blockquote>
  
  <pre><code>var express = require("express");
  var http = require("http");
  var path = require("path");
  var bodyParser = require("body-parser");
  var cookieParser = require("cookie-parser");
  var expressSession = require("express-session");
  var methodOverride = require("method-override");
  var morgan = require("morgan");
  var passport = require("passport");
  var randToken = require('rand-token');
  var jwt = require("jsonwebtoken");
  
  //var mongoose = require("mongoose");
  var app = express();
  
  //MongoDB
  //=============================================================================
  require("./db");
  
  //Application configuration variables
  // =============================================================================
  app.set("port", process.env.PORT || 1000);
  app.set("env", "development");
  //Set JWT Private Key
  //=============================================================================
  process.env['JWT_PRIVATE_KEY'] = randToken.generate(64);
  //Set Process environment variables
  //=============================================================================
  process.env['RECAPTCHA_PRIVATE_KEY'] = ***** RECAPTCHA PRIVATE KEY *****;
  
  app.enable('trust proxy');
  
  app.use(bodyParser.urlencoded({
      extended: false
  }));
  app.use(bodyParser.json());
  app.use(cookieParser());
  
  // Express Session
  app.use(expressSession({
      secret: 'cookie_secret',
      name: 'cookie_name',
      proxy: true,
      resave: true,
      saveUninitialized: true
  }));
  
  // Passport Init
  app.use(passport.initialize());
  app.use(passport.session());
  
  
  // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
  app.use(methodOverride('X-HTTP-Method-Override'));
  
  //Serving Static Direcotries
  //=============================================================================
  require("./utils")(express, app, path);
  
  app.all('/*', function (req, res, next) {
      console.log(req.headers);
      // CORS headers
      res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
      res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
      // Set custom headers for CORS
      res.header('Access-Control-Allow-Headers', 'Content-type,Accept,Authorization');
      console.log(" :::: Content-type :::: ");
      console.log(req.headers['Content-type']);
      if (req.method === 'OPTIONS') {
          res.status(200).end();
      } else {
          next();
      }
  });
  
  
  //Routes
  //=============================================================================
  
  // Application Routes
  var router = express.Router();
  
  //Default routes executes in every request
  router.use(function (req, res, next) {
      //res.json({message: "AquireConsole default routing executed"});
      var token;
      if (req) { // In a separate `if` because it is common to all the tests
          if (req.body &amp;&amp; req.body.token) {
              token = req.body.token;
          } else if (req.query &amp;&amp; req.query.token) {
              token = req.query.token;
          } else if (req.headers &amp;&amp; req.headers['Authorization']) {
              token = req.headers['Authorization'];
          }
      }
      console.log(" :::: Authorization :::: ");
      console.log(token);
      next();
  });
  
  // router.get("#/", function (req, res) {
  //    res.sendFile(basePath + "bin/client/app/views/index.html");
  // });
  
  app.use(require('../app/data/routes/user'));
  router.get("*", function (req, res) {
      res.sendFile(basePath + "app/client/views/index.html");
  });
  app.use("*", router);
  //Error handlers
  //=============================================================================
  
  //Development error handler will print stacktrace
  if (app.get('env') === "development") {
      router.use(function (err, req, res, next) {
          res.status(err.status || 500);
          res.render('error', {
              message: err.message,
              error: err
          });
      });
  }
  
  //Error handlers: no statistics leaked to user
  router.use(function (err, req, res, next) {
      res.status(err.status || 500);
  //    res.render('error', {
  //        message: err.message,
  //        error: {}
  //    });
  });
  //Instantiation of app
  //=============================================================================
  http.createServer(app).listen(app.get('port'), function () {
      console.log('AquireConsole is listening on port ' + app.get('port'));
  });
  // expose app
  exports = module.exports = app;
  </code></pre>
  
  <blockquote>
    <p>User.js [Express]</p>
  </blockquote>
  
  <pre><code>router
      .route("/api/user/logout")
      .post(
              function (req, res, next) {
                  req.logout();
                  res.json({status: 1, message: "Session windup"});
              }
      );
  </code></pre>
  
  <blockquote>
    <p>NodeJS Console response</p>
  </blockquote>
  
  <pre><code>{ 
        host: 'localhost:1000',
        'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:44.0) Gecko/20100101 Firefox/44.0',
        accept: 'image/png,image/*;q=0.8,*/*;q=0.5',
        'accept-language': 'en-US,en;q=0.5',
        'accept-encoding': 'gzip, deflate',
        referer: 'http://localhost:1000/css/style.css',
        cookie: 'cookie_name=s%3A94jdWCuOndbOnuR3jncf37yHkXPCJomq.Ye8aX%2B7xMio9amQ79QENe0wrLBykvUF4N43rfQs4cpU',
  
        connection: 'keep-alive',
        'cache-control': 'max-age=0'
      }
      :::: Content-type ::::
      undefined
  
      :::: Authorization ::::
      undefined
  </code></pre>
  
  <blockquote>
    <p>Browser Console Response </p>
  </blockquote>
  
  <p><a href="https://i.stack.imgur.com/6dXU0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6dXU0.png" alt="enter image description here"></a></p>