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;