Question

I am working on an API using djang-tastypie as backend and AngularJs for front end. I am sending request fro CRUD using angularjs $http. GET, POST, PUT everything is fine but when I am trying to send a PATCH request there is error Method PATCH is not defined. I have created a factory of api calls in angular but PATCH request is not working there.

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

this my HTML code

<div ng-app="myApp">
<div ng-controller="MyCtrl">
<button type="button" ng-click="edit()">Edit</button>
</div></div>

when i send a path request using this code in console it shows http.patch is not a function. Tell me how can i configure ng-app and services to send a PATCH request using angularjs.

Was it helpful?

Solution

A common issue with adding PATCH to AngularJS is that it doesn't have a default Content-Type header for that HTTP method (which is application/json;charset=utf-8 for PUT, POST and DELETE). And these are my configuration of the $httpProvider to add patch support:

module.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.patch = {
    'Content-Type': 'application/json;charset=utf-8'
}
}])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top