简体   繁体   中英

React: How to get a Django CSRF Token if CSRF_TOKEN_HTTPONLY is true?

I'm building a React application for a Django backend. In the backend the security setting CSRF_TOKEN_HTTPONLY is set to True . How can I obtain this csrf token in a React app? The documentation only describes how to do that using jquery. I'm usin the fetch API for my http requests.

If you include the csrf token in your HTML like the documentation says:

{% csrf_token %}

Then you can simply get the token like this:

var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]").value

And do your requests with the Fetch API this way:

fetch(url, {
    credentials: 'include',
    method: 'POST',
    mode: 'same-origin',
    headers: {
      'X-CSRFToken': csrftoken
    },
    body: {}
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM