advfe-unified-workspace

Advanced Front End: Adding the route to serve the index template

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:

  1. Remove the root_route view from the .views imports

    a settings.py file with the root_route import removed

  2. Import the TemplateView from the generic Django views

     from django.views.generic import TemplateView
    

    a settings.py file with a TemplateView import

  3. 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:

    a URL patterns list with root_route next to a blank path

    After:

    a URL patterns list with a TemplateView next to a blank path

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

    a handler404 variable in a settings.py file

  5. Add api/ to the beginning of all the API URLs, excluding the path for the home page and admin panel

    api/ prepended to several URL patterns

In axiosDefault.js:

  1. 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"

    axios defaults baseurl set with api/

This would be a good point to commit your changes again.

Up Next

We explain how to compile the static files.