我正在使用djang-tastypie作为后端和AngularJs作为前端的API。我正在使用angularjs $ http向CRUD发送请求。 GET,POST,PUT一切都很好,但是当我尝试发送PATCH请求时,会出现错误方法PATCH未定义。我已经创建了一个有角度的api调用工厂,但PATCH请求不在那里工作。
angular.module('tastypieModule', ['ngResource']).
factory('apiCall', function($http, $resource) {
delete $http.defaults.headers.common['X-Requested-With'];
var apiCall = $resource('/api/v1/:type/:id/',
{type: '@type', username: '@userName', api_key: '@api_key', user: '@userID', id: '@id'},
{
get: {method: 'GET'},
post: {method: 'POST', headers: {'Content-Type': 'application/json'}},
del: {method: 'DELETE', headers: {'Content-Type': 'application/json'}},
update: {method: 'PUT', headers: {'Content-Type': 'application/json'}},
pupdate:{method:'PATCH',headers: {'Content-Type': 'application/json'}}
}
);
return apiCall;
});
function MyCtrl($scope,$resource){
$scope.edit=function(){
id=$scope.E_id
$http.pupdate('/api/v1/quizsetting/'+id+'/', editedquizsetting).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.editQuizSettingModal = false;
//$scope.quizsettinglist.objects[$scope.e_quizsettingindex]=data;
$(".message").append("object has been created successfully");
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
这是我的HTML代码
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<button type="button" ng-click="edit()">Edit</button>
</div></div>
当我在控制台中使用此代码发送路径请求时,它显示http.patch不是一个函数。 告诉我如何配置ng-app和服务以使用angularjs发送PATCH请求。
答案 0 :(得分:18)
向AngularJS添加PATCH的一个常见问题是它没有该HTTP方法的默认Content-Type标头(对于PUT,POST和DELETE,它是application / json; charset = utf-8)。这些是$ httpProvider的配置,用于添加补丁支持:
module.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.patch = {
'Content-Type': 'application/json;charset=utf-8'
}
}])