Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new headers to the http request in angularjs through interceptors?

Tags:

angularjs

var module = angular.module('timestamp-marker-example', []);
        module.factory('timestampMarker',[function() {
            var timestampMarker = {
                request: function(config) {
                    console.log(config);
                    console.log(config.method);
                    console.log(config.url);
                   /* console.log(config.headers);*/
                    var head={
                            headers:{
                                'X-testing':'testing'
                            },
                            method:"POST"
                    }
                    config.push(head);      



                    return config ;
                },
                response: function(response) {

                   return response;
                }
            };
            return timestampMarker;
        }]);
        module.config(['$httpProvider', function($httpProvider) {
            $httpProvider.interceptors.push('timestampMarker'); 
        }]);

        module.controller('ExampleController', ['$scope', '$http', function($scope, $http) {

            $http.get('https://api.github.com/users/naorye/repos').then(function(response) {
                console.log(response);

            });
        }]);

I want to add new headers to the request from the interceptors. How to add it? I have tried in the above code. Can anyone help me solve this problem?

like image 499
Vindya Veer Avatar asked Dec 19 '22 00:12

Vindya Veer


1 Answers

Config :

app.config([ '$httpProvider',   function($httpProvider) {
    $httpProvider.interceptors.push('APIInterceptor');
} ]);

Service :

app.service('APIInterceptor', [function() {
    var service = this;

    service.request = function(config) {
        config.headers.YOUR_HEADER= YOUR_HEADERS_VALUE;
        return config;
    };
}]);
like image 179
ThibaudL Avatar answered May 20 '23 20:05

ThibaudL