Search code examples
javascriptdjangopostcsrffetch

Django as API + ReactJS - Redux: POST request with CSRF token but still response CSRF Token not set


After looking around I wanted to be sure that I'm doing it right but I start doubting and worst: I'm running out of options / ideas.

So I'm using django as an API like (I do only get request for some assets) except for one POST method within a base class view to allow my user to download files.

The problem is that django expect a CSRF token on my POST.

So, here is what I do from my reactjs:

export function sendData(endpoint, req, data) {
return dispatch => {
    dispatch(requestData(data));
    let csrfToken = Cookies.get('csrftoken');

    return fetch(endpoint, {
        method: req,
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrfToken,
        },
        body: JSON.stringify(data),
    })
    .then(checkStatus)
    .then(reponse => {
        console.log("Success!");
    }).catch(err => {
        err.response.json().then((json) =>{
            let { Errors, Result } = json;
            console.log('request failed: ', Errors, " ", Result);
        });
    });
};

};

As you can see, I'm using the 'whatwg-fetch' library. I've tried to replace the X-CSRFToken by X-CSRF-Token but the request is blocked to the chrome "option" and doesn't seem to be properly sent: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.

But I still get the error I've been reading about everywhere:

CSRF verification failed. Request aborted. Reason given for failure: CSRF cookie not set.

Urgh.

What am I missing here?

On my view I've tried every kind of decorators even this:

class DownloadAssetsView(ViewUrlMixin, ListView):
    @csrf_exempt
    def post(self, request, *args, **kwargs):
        print(request)
        return HttpResponse("coucou", status=200, content_type='application/json')

But I can't make it work..

PS: django has no template rendering to my client side, at all.


Solution

  • we had this problem in our project.the csrf token made to block unkown token and request.if you see the doc about csrf token you can find that.the csrf token blocks your external request to your django server.we merge the react project to our django.it fixed.try that .im not expert on this but you can check this out.