API Fetch POST Django

jQuery React/Redux/Django webapp $.ajax Fetch API. GET, , , , POST, , POST Django request.POST . , /sign _in, request.POST . Django ( Django, , React), , request.body request.data.

Here is all the code that I might think would be relevant, please let me know if there is more, which would be useful:

This is the explicit function that I use to create my full POST data and attach the CSRF token:

const setUpCsrfToken = () => {
  const csrftoken = Cookies.get('csrftoken')

  return function post (url, options) {
  const defaults = {
    'method': 'POST',
    'credentials': 'include',
    'headers': {
      'X-CSRFToken': csrftoken,
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }

  const merged = merge(options, defaults)
  return fetch(url, merged)
  }
}

export const post = setUpCsrfToken()

This is the API method that I use from the React application:

export const signIn = data => {
  return post('/api/account/sign_in/', data)
}

The data, when originally packaged in the React application itself, is as simple as an object with string values:

{
    email: 'email@email.com',
    password: 'password
}

I looked through these questions and found them useful, but I can’t figure out how to synthesize an answer for myself that takes into account what I assume are some of the difficulties of Django:

question

question

question

question

Thank!

+4
source share
1 answer

X-Requested-With. jQuery .

X-Requested-With: XMLHttpRequest

, - :

const setUpCsrfToken = () => {
  const csrftoken = Cookies.get('csrftoken')

  return function post (url, options) {
    const defaults = {
      'method': 'POST',
      'credentials': 'include',
      'headers': new Headers({
        'X-CSRFToken': csrftoken,
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest'
      })
    }

    const merged = merge(options, defaults)
    return fetch(url, merged)
  }
}
+3

Source: https://habr.com/ru/post/1679932/


All Articles