Search code examples
angularjsangular-resource

How to set headers in multiple $resources inside factory in AngularJs


I have tried to add a custom header to my request.But when i added i got the following error and my REST call doesn't execute.

Console error

SyntaxError: Unexpected token M
    at Object.parse (native)
    at fromJson  (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js:1231:14)
at defaultHttpResponseTransform ...

Sample Code snippet

var testModule = angular.module(
        'test',
        [ 'ngAnimate', 'ngTouch', 'ui.grid', 'ngResource', 'ngLoadingSpinner',
                'ui.grid.pagination','ui.select','ui.grid.resizeColumns']).factory(
        'myService',
        function($resource) {

            return {
                Jobs : $resource('/executionjob/jobs', {},{
                     get: {
                            method: 'GET',
                            headers : {
                                'Accept' : 'application/json',
                                'Content-Type' : 'application/json',
                                'Api-Key' : authToken.apiKey()
                            }

                        }   
                }),
                ScheduleJobs : $resource(
                        '/executionjob/scheduleJob', null, {
                            'cancelJobs' : {
                                method : 'PUT'
                            }
                        }),
            };
        });

without headers REST services works fine.But for my future requirements i want to add some security to my REST endpoints.Note: I also know there are some duplicate questions but my question is different from them because i am using one factory with the multiple $resources.Please let me know how can i add custom headers to my REST call and is there any way to add common header to all of REST requests.


Solution

  • Yes, you can add common header like below:

    angular.module('test', [])
    .config(['$httpProvider', function($httpProvider) {
      $httpProvider.defaults.headers.common["Accept"] = 'application/json';
      $httpProvider.defaults.headers.common["Content-Type"] = 'application/json';
    }])