Search code examples
angularjsangular-resourceangularjs-factory

How can i set default param in ngResource to be POST


I have a simple AJAX request that needs a csrf token for every call and i define it like so:

app.factory('auth', ['$resource', '$cookies', function($resource, $cookies){

    var getCsrf = function() {
        //get csrf token from cookie
    };

    return {
        login: $resource('auth/login', {}, {
                'q' : {
                    method: 'POST',
                    params: {csrf_token: getCsrf()}
                }
            }),
        // ... some more requests
    };
}]);

As i understood it you can specify the default url parameters as second param of the $resource()-call, in my case the empty object {}. Apparently the data i set in the configurations object under params: ... also gets send via GET and not with the specified POST-method.

One way would be to manually put the csrf_token in where i make the call to the api-function, but i'd like to keep it clean. Is there a way to tell angular what method to use for the default params? So i could simply use ..

auth.login.q(email, password, ...).then( ... );

.. without having to implement the csrf-getter function into all my calls. Also i am relatively new to AngularJS so a simple answer would be great!


Solution

  • There is an easy way to this in angular: set the xsrf cookie name and header name defaults in the config module.

    app.config(['$httpProvider', function($httpProvider) {
        // response cookie name
        $httpProvider.defaults.xsrfCookieName = 'csrf_cookie';
        // request header name where the value of the cookie get set
        $httpProvider.defaults.xsrfHeaderName = 'HTTP_X_XSRF_TOKEN';
    
        // to set ajax request header
        $httpProvider.defaults.headers.common = { 'X-Requested-With' : 'XMLHttpRequest'};
    }