简体   繁体   English

使用React和axios禁止(未设置CSRF cookie)

[英]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/" 我一直在React中使用一个登录组件,该组件可以将用户名和密码信息发送到django主机127.0.0.1:8000/api-auth/login/,当我尝试发送时,django服务器显示此消息“ Forbidden (未设置CSRF cookie。):/ 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. 我曾尝试在我的应用程序设置中检查django cors选项,但没有任何效果,我也尝试发送一些标头以及发布请求。

This is my cors settings 这是我的cors设定

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_exempt

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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