Every time I try to run the code, I get an error that a CSRF token is missing.
I have tried adding the token in the html and then adding an event listener for the form but that did not work as I still got the error and the console linked it to the line where I fetched a url.
Attempt: (the {{ form }} is a django form which contains a textarea)
<div id="add-form">
<form action="" id="form-add">
{% csrf_token %}
<h2>New Post</h2>
{{ form }}
<input type="submit" value="Post" />
</form>
</div>
// Javascript
document.querySelector('#form-add').onsubmit = submit // submit is the function with the fetch command
So instead I used babel to add the form into the html (this was not to fix the problem).
I have tried to manually add a CSRF token to the react form but I still got the same error:
Forbidden (CSRF token missing.): /post.
I also tried to add it using a JQuery function I found here (django documentation) but it did not work probably because every time I added the CSRF token in the form I still got the error.
So how do I add a csrf token to a fetch command in javascript?
html:
<div id="add-form">
</div>
js:
ReactDOM.render(<Form />, document.querySelector('#add-form'));
// Apps
function Form() {
return (
<div>
<form id="form-add" onSubmit={submit}>
<input type="hidden" name="csrfmiddlewaretoken" value="uhTD3vSjaOhnEC2Bda0bgRW5rzvFMTCRnQoX2aRDP2RDHMtP2YEqhaHDQvMbb9h0" />
// attempt to manually add CSRF token
<h2>New Post</h2>
<textarea id='content' maxLength='500' required autoComplete='off' placeholder='Share something' />
<input type="submit" value="Post" />
</form>
</div>
)
}
// Functions
function submit(event) {
event.preventDefault();
fetch('/post', {
method: 'POST',
body: JSON.stringify({
'content': document.querySelector('#content').value
}),
// make sure the server knows this is a JSON body
headers: {
'Content-Type': 'application/json',
// Add CSRF token
// "X-Requested-With": "XMLHttpRequest"
},
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
}).catch(error => {
console.log('Error:', error);
});
document.querySelector('#content').value = ''
}