How to use CSRF protection with AJAX In Django
When making AJAX or API requests from JavaScript, we need to manually include the CSRF token in the request headers.
Assume that we have a page where we want to send data to a Django API endpoint using AJAX. We need to include the CSRF token as a header in our AJAX request. We can acquire the token as shown in the below example:
The JavaScript code in the HTML page extracts the CSRF token from the cookie using the getCookie
function and sends a POST request to the Django API endpoint.
HTML
<!DOCTYPE html> < html > < head > < title >API Request Example</ title > < script > // Function to get the CSRF token from the cookie function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } // Function to send a POST request with CSRF token function sendPostRequest() { const csrfToken = getCookie('csrftoken'); const url = '/api/some_endpoint/'; const data = { key: 'value' }; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken // Include the CSRF token in the header }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Response from server:', data); }) .catch(error => { console.error('Error:', error); }); } </ script > </ head > < body > < button onclick = "sendPostRequest()" >Send POST Request</ button > </ body > </ html > |
CSRF token in Django
Django provides a feature known as a CSRF token to get away from CSRF attacks that can be very dangerous. when the session of the user starts on a website, a token is generated which is then cross-verified with the token present with the request whenever a request is being processed.
Contact Us