简体   繁体   English

csrf 令牌缺少 axios 到 django rest 框架

[英]csrf token missing axios to django rest framework

i was trying to make post request and face with error code 403,csrf token was missing.. tried many methods but didnt work at last disabled csrf token on settings.py and worked, so found the problem was in csrf token我试图发出发布请求并面对错误代码 403,csrf 令牌丢失.. 尝试了很多方法,但最后没有在 settings.py 上禁用 csrf 令牌并工作,所以发现问题出在 csrf 令牌中

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',
      })
    
      .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;

this is my code pls tell me a way to put csrf token in this as well as import statement...这是我的代码,请告诉我一种将 csrf 令牌放入其中的方法以及导入语句...

currently using axios thanks目前使用 axios 谢谢

There are three ways.有三种方式。 You can manually include the token in the header of each axios call, you can set axios's xsrfHeaderName in each call, or you set a default xsrfHeaderName .您可以在每个 axios 调用的 header 中手动包含令牌,您可以在每个调用中设置 axios 的xsrfHeaderName ,或者设置一个默认的xsrfHeaderName

1. Adding it manually 1.手动添加

Let's say you've got the value of the token stored in a variable called csrfToken .假设您将令牌的值存储在名为csrfToken的变量中。 Set the headers in your axios call:在 axios 调用中设置标题:

// ...
method: 'post',
url: '/api/data',
data: {...},
headers: {"X-CSRFToken": csrfToken},
// ...

2. Setting xsrfHeaderName in the call: 2.在调用中设置xsrfHeaderName

Add this:添加这个:

// ...
method: 'post',
url: '/api/data',
data: {...},
xsrfHeaderName: "X-CSRFToken",
// ...

Then in your settings.py file, add this line:然后在您的settings.py文件中,添加以下行:

CSRF_COOKIE_NAME = "XSRF-TOKEN"

3. Setting default headers 3.设置默认标题

Rather than defining the header in each call, you can set default headers for axios.您可以为 axios 设置默认标头,而不是在每个调用中定义 header。

In the file where you're importing axios to make the call, add this below your imports:在您要导入 axios 以进行调用的文件中,将其添加到您的导入下方:

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

Then in your settings.py file, add this line:然后在您的settings.py文件中,添加以下行:

CSRF_COOKIE_NAME = "XSRF-TOKEN"

check this answer检查这个答案

this is an example of how to add it manually:这是如何手动添加它的示例:

class Axios extends React.Component{    

constructor(){
    super()
    this.state = {
        persons: []
    }
}
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var CSRF_TOKEN=getCookie('csrftoken');
post(){
    axios.post('http://127.0.0.1:8000/api/create', {
        title: 'titan',
        body: 'this is working',
    headers:{
                    '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;

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

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