ataraxis
ataraxis

Reputation: 1582

Access API from backend from React directly on the server

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?

Upvotes: 0

Views: 291

Answers (1)

onuriltan
onuriltan

Reputation: 3908

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'
  )

Upvotes: 1

Related Questions