如何使用Django和AngularJS创建POST请求(包括CSRF令牌) [英] How to create a POST request (including CSRF token) using Django and AngularJS

查看:75
本文介绍了如何使用Django和AngularJS创建POST请求(包括CSRF令牌)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angular.js创建一个POST请求到这个Django视图。

  class PostJSON4SlickGrid(View) :

REST POST SlickGrid更新工作包的接口


def post(self,request,root_id,wp_id,** kwargs) :
printin PostJSON4SlickGrid
print request.POST
return HttpResponse(status = 200)

因此我创建了这个资源。

  myModule.factory('gridData',function ){
// define resource class
var root = {{root.pk}};
return $ resource('{%url getJSON4SlickGrid root.pk%}:wpID /',{ wpID:'@ id'},{
get:{method:'GET',params:{},isArray:true},
update:{method:'POST'}
} );
});

调用控制器中的 get 方法工作正常。该URL被翻译成 http://127.0.0.1:8000/pm/rest/tree/1/

 函数gridController($ scope,gridData){
gridData.get(function(result){
console.log(result);
$ scope .treeData = result;
//广播异步xhr调用完成
$ scope。$ broadcast('mySignal',{fake:'Hello!'});
});
}

当我面临执行更新/ POST方法的问题。

  item。$ update(); 

URL被翻译成 http://127.0.0.1:8000/ pm / rest / tree / 1/345 ,缺少尾部斜线。当您的URL定义中不使用尾部斜线时,这可以轻松绕过。

  url(r'^ rest / tree /( ?P< root_id> \d +)/(?P< wp_id> \d +)$',PostJSON4SlickGrid.as_view(),name ='postJSON4SlickGrid'),
p $ p

而不是

  url(r'^ rest / tree / (?P< root_id> \d +)/(?P< wp_id> \d +)/ $',PostJSON4SlickGrid.as_view(),name ='postJSON4SlickGrid'),
/ pre>

使用没有尾部斜杠的解决方法我现在得到一个403(禁止)状态代码,这可能是因为我没有通过 CSRF 令牌。因此,我的问题归结为如何将CSRF令牌传递给由角度创建的POST请求?



我知道关于这个方法通过头文件传递csrf令牌,但是我正在寻找一个可能性,将标记添加到帖子请求的正文中,如此处所示。添加数据到岗位请求正文是否有可能?



作为附加读数,可以查看有关资源的这些讨论,删除尾部斜线以及当前的限制资源具有: disc1 盘2
在其中一个讨论中,其中一位作者建议目前不使用资源,而是使用这种方法。

你不能这样打电话:

  $ http({
method:'POST',
url:url,
data:xsrf,
headers:{'Content-Type ':'application / x-www-form-urlencoded'}
})

数据可以是您希望通过的任何东西,然后只需将& {{csrf_token}} 在您的资源 params:{} 中,尝试添加 csrfmiddlewaretoken:{{csrf_token}}



$ params



编辑:



您可以将数据传递到请求正文,如

 项目$ update({csrfmiddlewaretoken:{{csrf_token}} })

和标题为

  var csrf ='{{csrf_token}}'; 
update:{method:'POST',headers:{'X-CSRFToken':csrf}}

这是一个无证的问题


I'm trying to create a POST request using angular.js to this Django view.

class PostJSON4SlickGrid(View):
    """
    REST POST Interface for SlickGrid to update workpackages
    """

    def post(self, request, root_id, wp_id, **kwargs):
        print "in PostJSON4SlickGrid"
        print request.POST
        return HttpResponse(status=200)

Therefore I created this resource.

myModule.factory('gridData', function($resource) {
    //define resource class
    var root = {{ root.pk }};
    return $resource('{% url getJSON4SlickGrid root.pk %}:wpID/', {wpID:'@id'},{
            get: {method:'GET', params:{}, isArray:true},
            update:{method:'POST'}
    });
});

Calling the get method in a controller works fine. The url gets translated to http://127.0.0.1:8000/pm/rest/tree/1/.

function gridController($scope, gridData){
    gridData.get(function(result) {
        console.log(result);
        $scope.treeData = result;
        //broadcast that asynchronous xhr call finished
        $scope.$broadcast('mySignal', {fake: 'Hello!'});  
    });
}

While I m facing issues executing the update/POST method.

item.$update();

The URL gets translated to http://127.0.0.1:8000/pm/rest/tree/1/345, which is missing a trailing slash. This can be easily circumvented when not using a trailing slash in your URL definition.

url(r'^rest/tree/(?P<root_id>\d+)/(?P<wp_id>\d+)$', PostJSON4SlickGrid.as_view(), name='postJSON4SlickGrid'),

instead of

url(r'^rest/tree/(?P<root_id>\d+)/(?P<wp_id>\d+)/$', PostJSON4SlickGrid.as_view(), name='postJSON4SlickGrid'),

Using the workaround without the trailing slash I get now a 403 (Forbidden) status code, which is probably due to that I do not pass a CSRF token in the POST request. Therefore my question boils down to how I can pass the CSRF token into the POST request created by angular?

I know about this approach to pass the csrf token via the headers, but I m looking for a possibility to add the token to the body of the post request, as suggested here. Is it possible in angular to add data to the post request body?

As additional readings one can look at these discussions regarding resources, removed trailing slashes, and the limitations resources currently have: disc1 and disc2. In one of the discussions one of the authors recommended to currently not use resources, but use this approach instead.

解决方案

Can't you make a call like this:

$http({
    method: 'POST',
    url: url,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

The data can be whatever you wish to pass and then just append &{{csrf_token}} to that.

In your resource params:{}, try adding csrfmiddlewaretoken:{{csrf_token}} inside the params

Edit:

You can pass data to the request body as

item.$update({csrfmiddlewaretoken:{{csrf_token}}})

and to headers as

var csrf = '{{ csrf_token }}'; 
update:{method:'POST', headers: {'X-CSRFToken' : csrf }} 

It is an undocumented issue

这篇关于如何使用Django和AngularJS创建POST请求(包括CSRF令牌)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆