我正在使用 AngularJS 以及 Python & Django 和 Django REST API。 REST API 创建了一个 JSON 文件,我需要使用 Angular $http.post() 将数据发布到其中。
我需要知道这是否可能。
我主要收到 403(Forbidden) 和 400(BAD REQUEST) 错误..
$http({
method: 'POST',
url: '<JSON FILE URL>',
data: $scope.tmpDataSet,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}});
这是我的 .post() 方法。我在哪里从以 Angular 制作的表单中获取数据并将其存储在“tmpDataSet”中。它被正确创建并且无法存储到数组中。我只是无法将其写入 JSON 文件。
我的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
}
]
如果需要更多代码细节,请发表评论。
请您参考如下方法:
这个问题可以通过将 CSRF token 添加到 Angular 应用程序并使用带有所有参数的常规 $http.post() 函数来解决。
app.config(function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
和,
$http.post('<URL>', item).error(function(data,status,headers,config){
console.log('COULDNT POST!');
}).success(function(data, status, headers, config){
console.log('POSTED!');
});
