[Answered ]-How can I send a CSRF token in a form?

1👍

First, acquire the token from the csrftoken cookie:

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

…or from querying the document:

const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value

Then, add the token value to your POST header:

axios.post('MY_URL', {
    price: this.price,
    amount: this.amount,
  }, {
    headers: {
      'X-CSRFToken': csrftoken
    }
  })
👤tony19

Leave a comment