简体   繁体   English

在AngularJS中的JSON文件中发布数据-(在此处使用django REST创建该JSON文件。)

[英]Posting data in a JSON file in AngularJS - (using django REST here to create that JSON file.)

I am using AngularJS along with Python & Django and Django REST API. 我正在将AngularJS与Python&Django和Django REST API一起使用。 There is a JSON file created by the REST API and I need to post data into it using Angular $http.post() . REST API创建了一个JSON文件,我需要使用Angular $http.post()将数据发布到其中。

I need to know if it is possible or not. 我需要知道是否有可能。

Im majorly getting 403(Forbidden) and 400(BAD REQUEST) errors on post.. 我在发布时主要收到403(禁止访问)和400(错误请求)错误。

$http({
       method: 'POST',
       url: '<JSON FILE URL>',
       data: $scope.tmpDataSet,
       headers: {'Content-Type': 'application/x-www-form-urlencoded'}

 }});

This is my .post() method. 这是我的.post()方法。 where im fetching the data from a form made in angular and storing it in 'tmpDataSet'. 在这里,我从有角度的表单中获取数据并将其存储在“ tmpDataSet”中。 Its being created properly and im able to store into the array. 它被正确创建,并且无法存储到阵列中。 Im just not able to write it into the JSON file. 我只是无法将其写入JSON文件。

The structure of my JSON file is 我的JSON文件的结构是

{
    "count": 6,
    "next": null,
    "previous": null,
    "results": [
        {
            "name": "fff",
            "mobile_no": "fff",
            "email": "n@gmail.com",
            "message": "dfdf",
            "id": 1
        },
        {
            "name": "asd",
            "mobile_no": "0987654321",
            "email": "asd@gmail.com",
            "message": "no",
            "id": 2
        }
]

If any more code detail is needed please comment. 如果需要更多代码详细信息,请发表评论。

This issue was solved by adding CSRF tokens to the angular app and using the regular $http.post() function with all the parameters. 通过将CSRF令牌添加到angular应用程序并使用常规的$http.post()函数以及所有参数来解决此问题。

app.config(function($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});

and, 和,

$http.post('<URL>', item).error(function(data,status,headers,config){
            console.log('COULDNT POST!');
        }).success(function(data, status, headers, config){
            console.log('POSTED!');
        });

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

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