简体   繁体   中英

Forbidden (CSRF cookie not set.) with React and axios

I have been working with a login component in React which can send the username and password information to the django host 127.0.0.1:8000/api-auth/login/ and when I try to send it, the django server shows this message "Forbidden (CSRF cookie not set.): /api-auth/login/"

I have tried checking the django cors options in my app settings but nothing worked, also I tried sending some headers along with the post request.

This is my cors settings

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
        'http://localhost:3000',        
)
CORS_ALLOW_HEADERS = (
    'csrftoken',
    'content-type',
    'X-CSRFTOKEN'
)
CSRF_COOKIE_NAME = "csrftoken"
CSRF_HEADER_NAME = 'X-CSRFTOKEN'

This is my post request

handleSubmit = event =>{

     var csrfCookie = Cookies.get('csrftoken'); 
     console.log('csrf cookie: ', csrfCookie); // set to undefined

     axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
     axios.defaults.xsrfCookieName = "csrftoken";
     axios.defaults.withCredentials = true;

     axios
          .post( 'http://127.0.0.1:8000/api-auth/login/', {
                    username : this.state.username,
                    password : this.state.password
                },{
                    headers: {"csrftoken": csrfCookie},
                })
          .then(res => console.log('Results: ' + res))
          .catch(err => console.log('Login error: ' + err))
}

Note : I don't have @csrf_exempt on any of my views

请在您的设置文件中添加CSRF_COOKIE_SECURE = True

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