3

I need to send CSRF token when the user sign up with form provided.

However, since the signup/signin will be the first time to interact with django REST API, so I create a dummy GET request when the webpage is loaded to retrieve the CSRF token from django.

The token is retrieved and stored in cookie.

enter image description here

However, I still get Forbidden (CSRF cookie not set.) from django.

This is my axios POST request.

import axios from 'axios'
axios.defaults.xsrfCookieName = 'vcubes'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'

let req = {
    url: 'http://localhost:9000/vcubes/signup/',
    method : 'POST',
    headers: {
        'Content-Type': 'text/plain'
    },
    data: data
}

NOTE:

When I add withCredentials: true into headers in axios POST, the browser send OPTIONS request instead of POST.

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
Mervyn Lee
  • 1,957
  • 4
  • 28
  • 54

2 Answers2

2
  let csrftoken = Vue.$cookies.get('vcubes')

  return axios.post('', data, {
    headers: {
      'X-CSRFToken': csrftoken
    }
  }).then(response => {
    return response.data
  })

This is pretty similar to Shane's answer, but show's how to get the csrf token in Vue. If your problem is getting the cookie, then this SO answer should help you.

Joshua Swain
  • 571
  • 2
  • 4
  • 22
1

Here's what I use in django:

result = { "insert your key values here" }
data = JSON.stringify(result)
axios.post("{% url 'error_checking' %}", data, {headers: {'X-CSRFToken': '{{ csrf_token }}',}})
Shane Cheek
  • 143
  • 2
  • 12