1

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

Belhadjer Samir
  • 1,461
  • 7
  • 15
  • Does this answer your question? [Django CSRF check failing with an Ajax POST request](https://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request) – Ivan Starostin Mar 09 '21 at 15:55
  • using axios,not ajax.. –  Mar 09 '21 at 15:55
  • Axios does AJAX. Here is specifically for axios https://stackoverflow.com/questions/39254562/csrf-with-django-reactredux-using-axios Please use search. – Ivan Starostin Mar 09 '21 at 17:58

1 Answers1

2

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;
Belhadjer Samir
  • 1,461
  • 7
  • 15