With AngularJS, I don't want to set the global $http.defaults.headers.common. Can I send my custom header with each $resource call?

穿精又带淫゛_ 提交于 2019-12-05 13:54:25

Instead of this:

$http.defaults.headers.common['Authorization'] = cred;
return $resource('/api/cases/store').save();

Do this:

return $resource('/api/cases/store', {}, {
    save: {
        method: 'POST',
        headers: { 'Authorization': cred }
    }
}).save();

Note that you have to use 'save' as the action, the first key in the third parameter. Can't test it, so let me know if it works.

And I agree. The documentation doesn't talk about it. Take a look at the DEFAULT_ACTIONS list in the $resource source-code in angular-resource.js

The $resource documentation does cover it, though its certainly awkward to read. You have to make a custom action for it, and all the parameters you can pass to the config are NOT listed on the $resource page. You'll want to check out the $http docs page for the possibilities for the config object.

$resource() takes 3 arguments: the URL, the default parameters object, and the actions object. Actions map method names to $http configs, basically.

You want to make a custom action, something like:

var MyResource = $resource('/myendpoint/', {}, { 'post': { method: 'POST', headers: {"Authorization" : cred}}); // and any other $http options you might want

Those actions get turned into methods on the MyResource object, so you could name the action something more semantic than just "post" if you wanted (the examples on the docs page set up a "charge" action for a credit card resource, for instance).

The documentation for $http is pretty solid, as is most of the other documentation on their site.

And you can absolutely define your auth headers on each individual AJAX calls.

try something like this:

$http({
    method: 'POST',
    url: 'serverUrl',
    data: parameters,
    headers: { Authorization: cred }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!