VnC
VnC

Reputation: 2016

Django React Axios

I am trying to make a post request to a Django server using React with Axios. However, I am getting a redirect 302 on the server side.

Just followed all suggestions in this post here CSRF with Django, React+Redux using Axios unsuccessfully :(

However, what I have done so far is the following: Sat the default axios CookieName and HeaderName (on the javascript side):

axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.xsrfCookieName = "XCSRF-Token";

Got this in settings.py as well:

CSRF_COOKIE_NAME = "XCSRF-Token"

And here is how the post request looks like:

axios(
    {
        method: 'post',
        url: `/api/${selectedEntryType}_entry`,
        data: {
            "test": "test"
        },
        headers: {
            'X-CSRFToken': document.cookie.split('=')[1],
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/json',
        }
    }
)

Another thing that I have tried is to make the post request from the Django rest api UI: Django rest api UI

and it does work successfully.

The only differences in the Request Headers when I make the request from the UI and from JS are: Accept, Content-Length, and Referer, which I don't see how could they be problematic.

Please help.

Upvotes: 3

Views: 2897

Answers (1)

VnC
VnC

Reputation: 2016

Managed to fix it by changing the url (url:'/en/api/endpoint/') I was posting to, because apparently for a POST request:

You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/en/api/endpoint/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings

After that I started getting Forbidden 403, but by adding:

from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator

@method_decorator(csrf_protect)
def post(self, request):
    return Response()

and also changed the defaults in JS to:

axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.xsrfCookieName = "csrftoken";

and removed CSRF_COOKIE_NAME = "XCSRF-Token" from settings.py.

It worked.

Hope this helps somebody in the future.

Upvotes: 7

Related Questions