how to set custom headers with a $resource action?

headers for $resource is available since AngularJS 1.1.1. Make sure you have correct version used.

The format is

$resource('url/to/json', {}, {headers: { 'something': 'anything' }});

[edit by zuma] The above doesn't seem right. The third parameter to $resource should be a different. This seems more correct to me:

$resource('url/to/json', {}, {
    get: {
        method: 'GET',
        headers: { 'something': 'anything' }
    }
});

Demo Code

angular.module('Test',['ngResource'])
 .controller('corsCtrl', function ($scope, $http, MyResource) {

  $http.defaults.headers.common['test']= 'team'; //Using $http we can set header also
  MyResource.get();
})
.factory('MyResource', function($resource) {   //Services
  return $resource('url/to/json');
})

JsFiddle DEMO

see in Request Header

The headers object inside a resource action supports both static values for its fields, but also dynamic values returned from a function.

$resource('url/to/json', {}, {
        get: {
            method: 'GET',
            headers: { 
               'header_static': 'static_value',
               'header_dynamic': dynamicHeaderVal
            }
        }
});

function dynamicHeaderVal(requestConfig){
     // this function will be called every time the "get" action gets called
     // the result will be used as value for the header item
     // if it doesn't return a value, the key will not be present in the header
}

Tags:

Angularjs