'Django CSRF cookie sending images with axios client

Good day.

I need to send an image by the post method of a client with axios to a Django server but I get the following message on the server.

Forbidden (CSRF cookie not set.):

And the client gives me the following answer

xhr.js:177 POST http://127.0.0.1:8000/xxxx/ 403 (Forbidden)

How is it possible to solve this problem? It is possible to disable the CSRF cookie=

This is the client code:

    var formData = new FormData();
    formData.append("imagen", await fetch(`${filepath}`).then((e) => {
        return e.blob()
        })
        .then((blob) => {
            let b: any = blob
            b.lastModifiedDate = new Date()
            b.name = ''
            return b as File
        })
     );

    const axios = require('axios');
   
    axios({
        url:url,
        method:'POST',
        data:formData
    }).then(function(res: any){
        console.log(res)
    
    }).catch((error: any) =>{
        console.log(error)
       //Network error comes in
    });

And this is the server view function (It just check the info to debug)

def completeInfo (request): 
   print(request)
   return HttpResponse("Bad Response")


Solution 1:[1]

I had faced similar issue and using @csrf_exempt solved my problem.

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def completeInfo (request): 
   print(request)
   return HttpResponse("Bad Response")

Solution 2:[2]

If you want to keep the csrf checking, you'll need to supply it with the headers:

in your template:

<script>
  var csrfToken = "{{ csrf_token|escapejs }}";
</script>

then in your axios call:

axios({
    url:url,
    method:'POST',
    data:formData,
    headers: { 'X-CSRFToken': csrfToken }
})

and on the django side, settings.py:

MIDDLEWARE += ['django.middleware.csrf.CsrfViewMiddleware']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tasnuva
Solution 2 Barney Szabolcs