Configuring the route to allow the React front end to be viewed.
The React front end will be served from the domain’s root URL, so we need to ensure that this is the React part of the project and not the DRF interface you worked with when the projects were separate. So we will add the code below to ensure that the home page will display the React application. Any 404 errors redirect the user back to the React application where the request will be handled by the react-router-dom. We will also adjust our URLs so that all URLs for the DRF API contain /api/ to ensure that the API’s routes do not clash with the React application’s routes.
In the urls.py file of your Django Rest Framework application:
Remove the root_route view from the .views imports
Import the TemplateView from the generic Django views
from django.views.generic import TemplateView
In the url_patterns list, remove the root_route code and replace it with the TemplateView pointing to the index.html file
path('', TemplateView.as_view(template_name='index.html')),
Before:
After:
At the bottom of the file, add the 404 handler to allow React to handle 404 errors
handler404 = TemplateView.as_view(template_name='index.html')
Add api/
to the beginning of all the API URLs, excluding the path for the home page and admin panel
In axiosDefault.js:
Now that we have changed the base path for the API route, we need to prepend all API requests in our react application with /api
. Open the axiosDefaults.js file, comment back in the axios.defaults.baseURL and set it to "/api"
This would be a good point to commit your changes again.
We explain how to compile the static files.