Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting cookie.load('csrftoken') undefined in react

I am sending axios.put request on my Django back-end (DRF). I am using react. GET request seems to work nicely. This is my code:

const options =  {headers: 
  {"X-CSRFToken": cookie.load('csrftoken')
}}

axios
.put(`/api/shippers/${values.id}/`,values, options)
.then(res => {
  console.log(res)
  return res
})
.catch(err => {
  console.log(err);
})

But all I get in cookie.load('csrftoken') is undefined. Even though csrftoken is set on my browser cookies.

enter image description here

like image 369
ARKhan Avatar asked Sep 17 '25 06:09

ARKhan


1 Answers

I solved this mystery by myself. Actually, I could not able to read csrftoken cookie from the browser using react cookie.load function. Because, in my Django back-end CSRF_COOKIE_HTTPONLY is set to True. According to the documentation, if this value is set to True, you can not read the csrftoken value using JavaScript. The workaround was to set this value to False and now cookie.load working fine.

The similar is the case with session_id, that you must set SESSION_COOKIE_HTTPONLY to False.

like image 132
ARKhan Avatar answered Sep 23 '25 13:09

ARKhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!