W1ldworm W1ldworm - 1 year ago 135
Javascript Question

Change http request header without refresh in angularjs

I'm writing a website which uses ngRoute for changing pages.
for logging in a form will appear and when it's successful controller changes the http header for requests in the next steps.
bud the problem is that when I change the header, page should be reloaded if not, the Token would not be added to header.

Controller :

app.controller('catCtrl',['Api','$scope','$cookieStore','$rootScope',function (Api,$scope,$cookieStore,$rootScope) {
$scope.Login = function(){
Api.loginEmail($scope.log_email, $scope.pass, 'chrome', 'windows','').success(function(response){
$cookieStore.put('Auth-Key', 'Token ' + response.token);

$scope.is_Loggedin = true;
$scope.log_email = null;
$scope.pass = null;
$scope.error = response.error;

App.run :

app.run(['$cookieStore','$http',function($cookieStore, $http){

$http.defaults.headers.common['Authorization'] = $cookieStore.get('Auth-Key');

How can I change the header without reloading page.

Answer Source

so you want to add your token on further request after login.

You can try angular interceptor. Here is few Answers related how to add toke via interceptor.

Interceptor Example 1

Interceptor example 2

sample Code:

app.factory('httpRequestInterceptor', function () {
  return {
    request: function (config) {    
      config.headers['Authorization'] = $cookieStore.get('Auth-Key');     

      return config;

In your service layer, Ignore verification this header for Login.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download