首页 > 解决方案 > 用户登录时csrf令牌不起作用反应js axios django

问题描述

当我注销并尝试发布时,它可以工作,但是当我登录并尝试发布时,它不起作用并给我 403 错误,

反应文件

class Axios extends React.Component{

constructor(){
    super()
    this.state = {
        persons: []
    }
}



post(){
    axios.post('http://127.0.0.1:8000/api/create', {
        title: 'titan',
        body: 'this is working',
    headers:{
                    withCredentials: true,
                    'X-CSRFToken':CSRF_TOKEN,
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
          })
        
      .then(function (response) {
        console.log(response);
    })
}

get(){
    axios.get('http://127.0.0.1:8000/api').then(Response=>{
        console.log(Response.data)
    })
}
componentDidMount(){

    this.post();
    this.get();
    
}



render(){
    return(
        <div>
            <h1>fetch</h1>
        </div>
    )
}
}

export default Axios;

视图.py

class create(CreateAPIView):

queryset = Post.objects.all()
serializer_class = postSerializers

还在setting.py中添加了这个

CSRF_COOKIE_NAME = "X-CSRFToken"

登录时

在此处输入图像描述

注销时

在此处输入图像描述

如果有足够聪明的人请帮我解决这个问题..试图找到解决方案好几天...

标签: reactjsdjangodjango-rest-frameworkaxioscsrf-token

解决方案


推荐阅读