How to set up Django Rest Framework + React

I have an application backend in Django-rest-framework and I have a react application.

How can I work together? For development, I open 2 terminals and run them separately. Is there some way to make them work together?

Also, in order to deploy it for production, I have no idea how I can do this. I tried to find a finished github project but couldn't find anything

Thank!

+3


source to share


2 answers


For dev:
You can run both of them on two different shells. By default your django rest api will be at 127.0.0.1:8000 and React will be at 127.0.0.1:8081. I don't think there will be any problem for the two to communicate through the fetch api. Just make sure you have ALLOWED_HOSTS=['127.0.0.1']

django.



For production:
It will work like any other mobile app or web app! Put your RESTful API on an app server (aws, heroku, or whatever you choose), and build and host your React app separately. Use Javascript fetch api to send requests to django endpoints and use json / xml response to render your views in React.

0


source


You should add CORS support for django if you are running on different servers.
Here the DRF package contains instructions on how to properly configure CORS.
Here's what you can do on the production server
in the main URLs:

# all your project urls
urlpatterns = [
   ... 
   url(r'^', TemplateView.as_view(template_name='index.html'), name='index')
]

      



TemplateView

at the end urlpatterns will match all requests that don't match previous urls. This view should serve as a template with the wepback package.
Then you do collectstatic and put nginx static in the static root as usual.
You can do the same in a development environment if you like.
And don't forget to change the root url for your backend api in your React app:

let ROOT = '/api/'
if (process.env.NODE_ENV !== 'production') {
    ROOT = 'http://127.0.0.1:8000/api/'
}
...

      

0


source







All Articles