告诉我如何向api发出POST请求。使用restangular

时间:2014-01-09 15:33:46

标签: javascript python django angularjs restangular

我使用的是Django REST框架。 如果您在页面上手动输入数据,则编写API无效:http://atata.com/en/api/v1/add_comment/

views.py(api)

class AddComment(generics.CreateAPIView):
"""
Create new comment.
Example API structure:
{
    "post_pk": 1,
    "name": "MyName",
    "email": "example@email.com",
    "text": "This is text message!"
}
"""
model = Comment
serializer_class = CommentSerializers

api有效。

controllers.js

var app = angular.module('controllers', []);

app.controller('CommentAddCtrl', function($scope, Restangular){
    $scope.logComment = function(mail, name, text){
        var url = window.location;
        var pk = url.hash.split('$pk:')[1];
        var url_add_comment_api = './en/api/v1/add_comment';

        if (mail === undefined || name == undefined || text === undefined)
            alert ('Error!');
        else {
            var comment = {
                  post_pk: pk,
                  name: name,
                  email: mail,
                text: text
                };
            this.add_comment = Restangular.all(url_add_comment_api).post(comment);
            }           
    };
});

当控制台出错时: POST http://atata.com/en/api/v1/add_comment/ 403(FORBIDDEN)

1 个答案:

答案 0 :(得分:0)

你可能在那里的某个地方遗漏了一个CSRF令牌。点击此处:Django Cross Site Request Forgery Protection