Background
I've been trying to make a POST request to my application's backend (written in Django) from my React frontend, but the request fails because the request does not include a CSRF token. Here is the code I use to setup and send my request:
const formData = new FormData()
// 'image' is a user uploaded image
formData.append(
"myImage",
image,
image.name
)
const data = await axios.post("http://localhost:8000/myendpoint", formData)
return data
My application is very simple in that there is no log-in/session-keeping that I need to do and to use the app the user simply needs to give some data (upload an image to be precise) to my Django API's endpoint and then get some results. For reference, here is what I see on my Django server logs:
Forbidden (CSRF cookie not set.): /myendpoint
And here is the error I see in the browser's console:
POST http://localhost:8000/myendpoint 403 (Forbidden)
Based on some questions that appear similar to mine, the suggestion seems to be to retrieve this CSRF token from the csrftoken
cookie that Django sends and then including it in subsequent POST requests (for instance, this answer). I didn't think this would work since I did not see any cookies in the Dev Window of the browser when at localhost:3000
, but I tried regardless and see the cookie as undefined:
CSRF Token: undefined
I used this code to try to get the cookie (using the js-cookie library):
var csrftoken = Cookies.get('csrftoken');
console.log(`CSRF Token: ${csrftoken}`)
Question(s)
Is there a way I can get the CSRF token cookie from Django before sending the POST request if that is the only request I'm sending? I know of some "hacky" ways such as using the csrf_exempt
decorator for my endpoint but I was wondering if there is a way I can make it work without it?
Thanks!