TodoApp Django-Rest-Framework React Redux notes

Last updated:
Hard to understand when visit localhost vs 127.0.0.1? Weird behaviors when SessionAuthentication? Wrong CSRFToken? Have a look!

Browser localhost

localhost and 127.0.0.1 are distinct.

Should use 127.0.0.1

So you know exactly the specific local IP. localhost can be anything based on the HOSTS file of your system (Windows, Linux, ...). You should visit 127.0.0.1 regardless your server is serving on localhost or 127.0.0.1 to have more control on set-cookie and sessionid and so on.

Django runserver

python manage.py runserver 8000
# will serve at 127.0.0.1:8000, only itself can visit
python manage.py runserver localhost:8000
# will serve at localhost:8000, only itself can visit
python manage.py runserver 0.0.0.0:8000
# will serve at its LAN IP, any device in LAN network can visit

Different localhost

Running server on localhost and 127.0.0.1 are different.
eg. Django sets csrftoken and sessionid on localhost then when you visit 127.0.0.1 won't have them.

SessionAuthentication

DRF's SessionAuthentication clashes with Django's SessionMiddleware ??

MIDDLEWARE = [
      ...
    'django.contrib.sessions.middleware.SessionMiddleware',
      ...
]

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

What happends?

Login via normal Django-template will go through Django's SessionMiddleware.
Login via DRF APIView will go through DRF's SessionAuthentication.

Axios Config options

import axios from "axios";

const instance = axios.create({
  baseURL: process.env.API_BASE_URL,
  withCredentials: true,
  withXSRFToken: true,  // Send XSRF header or not
  xsrfCookieName: "csrftoken", // Django sets this name
  xsrfHeaderName: "X-CSRFToken",  // Django expects this header
  timeout: 2000,
  headers: {
    "Content-Type": "application/json",
  },
});

Upgrade

  • Parcel -> 2.11.0
  • Axios -> 1.6.5

Check and upgrade non-breaking-changes

npm audit fix

Check and upgrade including breaking-changes

npm audit fix --force

> Blokquote

Comments

No comments!