0

I have been trying to send a simple post request to my django server using axios package in react. But everytime, I'm getting a backend error saying CSRF Cookie not set. Here is my React Code:

componentDidMount() {
    let csrfToken = getCsrfToken()
    console.log(csrfToken)
    axios({
        method: "POST",
        url: 'http://localhost:8000/getStats',
        headers: {
            "Content-Type": "application/json",
            "x-csrftoken": csrfToken
        },
        data: { "city": "pune" }
    }).then(response => {
        console.log(response);
    }).catch(err => {
        console.log(err);
    })
}

This is added in my django server: CSRF_COOKIE_NAME = "x-csrftoken"

Edit: I haven't yet used any form. I was just trying to send static data as Pune using axios when my component mounted.

2 Answers2

0

add the csrftoken to the data, I had the same problem with ajax, and Jquery

  [...]
  method: "POST",
        url: 'http://localhost:8000/getStats',
        headers: {
            "Content-Type": "application/json",
        },
        data: { "city": "pune" ,
                "csrfmiddlewaretoken": csrfToken}
  [...]
ThunderHorn
  • 1,975
  • 1
  • 20
  • 42
0

In Data Write

data: {
            'csrfmiddlewaretoken': '{{csrf_token}}',
            "city": "pune"
        },

also add {% csrf_token %}

<form>
  anywhere out this {% csrf_token %}
</form>
Waqas Devolper
  • 323
  • 2
  • 10