0

I am using Django as a backend and React for a frontend. I am starting the react frontend using PM2 and accessing the Django backend via PM2. I also installed Nginx as a reverse proxy to redirect querys to * mydomain.toplevel/admin to the django admin * mydomain.toplevel/ to the react frontend

The backend and frontend communicate via a REST api, using the DJANGO REST framework and Axios for React.

My main question at the moment is: Is it possible to let the frontend and the backend communicate directly on the server, in order of not exposing the API to the internet?

I guess not, because react, as a JS frontend, is executed on the client side - correct? Does this also hold if the React frontend is not served as static files (npm run-server build) but via PM2?

1 Answer 1

1

You can achieve it by only allowing your React application's domain. To do that;

  1. Install pip install django-cors-headers
  2. Add it to your installed apps
 INSTALLED_APPS = (
    'corsheaders',
    ...
 )
  1. Add middleware classes to settings.py:
   MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
       'corsheaders.middleware.CorsMiddleware',
       'django.middleware.common.CommonMiddleware',
       ...
  ]
  1. Add your React app's domain to allow it inside settings.py
  CORS_ORIGIN_ALLOW_ALL = False
  CORS_ORIGIN_WHITELIST = (
    'https://your-react-apps-domain',
    'http://localhost:3000'
  )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.