Django & React-Native: POST request between RN and Django

Shawnpy·2021년 9월 29일
0

Django & React-Native

목록 보기
10/14

POST request from React Native could be a little tricky at first, because there is no space to write CSRFToken unlike html. I used a form library Formik, which can work with a schema checking library yup well together.

CSRF Token - Django

First of all, I applied CSRF token exemption in Django backend server to avoid csrf token error from React Native. CSRF is to prevent from cross site request forgery, but as React Native is not using browers, we do not need it. HOWEVER, if you are going to use the same Django server to web service, you MUST NOT exempt csrf token. This is the setting to exempt csrf protection in Django server.

[settings.py]
# exempt csrf token check only for React Native

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}

POST request with Formik - React Native

<Formik
  initialValues={{ name: '' }}
  onsubmit={(values) => {
    let options = {
      method: POST,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
          name: values.name,
        })
      };
    fetch('http://127.0.0.0:8000/login/', options)
  }}
>

I will not go deeply about Formik. Let's focus on how to make the fetch() options. we can put method as POST and headers as we need. For body, the values need to be inserted in dictionary and JSON stringify.

profile
Do what you feel now

0개의 댓글