1
votes

I am sending a delete request with this code:

  $http({method: 'DELETE', url: '/url'}).
    success(function(status){
      //return status
    }).
    error(function(status){
    });

and I set csrf in app.run() as following:

 $http.defaults.headers.post['X-CSRFToken'] = getCookie("csrftoken");

GET and POST are working fine that means that the header contains a csrf token but while sending a DELETE request I am getting 403 Forbidden error and the status:

detail: "CSRF Failed: CSRF token missing or incorrect."

Is the anything extra I need to add to the header of the DELETE request?

1
try adding the header directly on the request, and see if that works. If that also doesnt work, its probable your getCOokie method that fails. - Nick
You've only added CSRF to POST requests. Try $http.defaults.headers.delete['X-CSRFToken'] as well - Phil
Ya that was the mistake. Thanks a lot - Ajeet Lakhani

1 Answers

1
votes

I would simply add an HTTP request interceptor to add the token to all POST / PUT / DELETE requests. For example

.config(function($httpProvider) {
    $httpProvider.interceptors.push(function() {
        return {
            request: function(config) {
                if (~['POST', 'PUT', 'DELETE'].indexOf(config.method)) {
                    config.headers['X-CSRFToken'] = getCookie("csrftoken");
                }
            }
        };
    });
})