简体   繁体   中英

CSRF verification failed error with react, axios and DRF

I am trying to make a post request which looks like this

axios
        .post(`http://127.0.0.1:8000/api/create/${this.props.id}`, {
          headers: {
            Authorization: `Token ${token}`
          },
          xsrfCookieName: "XSRF-TOKEN",
          xsrfHeaderName: "X-CSRFToken"
        })
        .then();

I have added essential things in settings.py also, such as CSRF_COOKIE_NAME = "XSRF-TOKEN"

I also have

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',


    ),
}

You may need to add ensure_csrf_cookie in your code.

A page makes a POST request via AJAX, and the page does not have an HTML form with a csrf_token that would cause the required CSRF cookie to be sent.

from django.views.decorators.csrf import ensure_csrf_cookie
 @ensure_csrf_cookie

Read more about ensure_csrf_cookie . Let me know if that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM