简体   繁体   中英

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. There is a JSON file created by the REST API and I need to post data into it using 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..

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

 }});

This is my .post() method. where im fetching the data from a form made in angular and storing it in 'tmpDataSet'. Its being created properly and im able to store into the array. Im just not able to write it into the JSON file.

The structure of my JSON file is

{
    "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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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