How do I send a CSRF token to a JSON API View?
Question by malero
I keep getting an error saying my csrf token is invalid. I've tried sending my request with 'csrf_token' in the json data, but that doesn't work. Any ideas on how to avoid using csrf_exempt for posting a form data to a view that accepts a JSON body?
const response = await fetch('/newsletter-signup/', {
method: 'POST',
headers: {
'accept': "application/json",
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.email,
csrf_token: this.csrf_token
}),
});
Answers
You have to include it in your headers with X-CSRFToken like this:
const response = await fetch('/newsletter-signup/', { method: 'POST', headers: { 'accept': "application/json", 'Content-Type': 'application/json', 'X-CSRFToken': this.csrf_token }, body: JSON.stringify({ email: this.email }), });
Answered by boomerkin