简体   繁体   中英

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

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...

currently using axios thanks

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 .

1. Adding it manually

Let's say you've got the value of the token stored in a variable called csrfToken . Set the headers in your axios call:

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

2. Setting xsrfHeaderName in the call:

Add this:

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

Then in your settings.py file, add this line:

CSRF_COOKIE_NAME = "XSRF-TOKEN"

3. Setting default headers

Rather than defining the header in each call, you can set default headers for axios.

In the file where you're importing axios to make the call, add this below your imports:

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

Then in your settings.py file, add this line:

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;

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