简体   繁体   English

如何在ngResource中将默认参数设置为POST

[英]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: 我有一个简单的AJAX请求,每次调用都需要一个csrf令牌,我这样定义它:

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 {} . 据我了解,您可以将默认的url参数指定为$resource()调用的第二个参数,在本例中为空对象{} Apparently the data i set in the configurations object under params: ... also gets send via GET and not with the specified POST-method. 显然我在配置对象中的params: ...下设置的数据params: ...也通过GET而不是通过指定的POST方法发送。

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. 一种方法是手动将csrf_token放在我对api函数进行调用的位置,但我想保持其清洁。 Is there a way to tell angular what method to use for the default params? 有没有一种方法可以告诉angular用于默认参数的方法? So i could simply use .. 所以我可以简单地使用..

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

.. without having to implement the csrf-getter function into all my calls. ..无需在我的所有调用中实现csrf-getter函数。 Also i am relatively new to AngularJS so a simple answer would be great! 我也是AngularJS的新手,所以一个简单的答案就好了!

There is an easy way to this in angular: set the xsrf cookie name and header name defaults in the config module. 在angular中,有一个简单的方法:在config模块中设置xsrf cookie名称和标头名称默认值。

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'};
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM