advfe-unified-workspace

Advanced Front End: Preparing React to connect to the Django API

We have a couple of things to do here, then we are ready to run the application.


Our unified workspace will now serve both the API and the React app, running on separate ports. As a result, in order for both apps to communicate successfully with each other while running on different ports, we will add a proxy to the React application’s package.json. This allows the React app to “pretend” it is making requests from the same port as the server and removes cross-domain issues.

package.json

  1. Open the package.json file in the frontend directory, and at the bottom of the file, add a new key to the JSON object

    "proxy": "http://localhost:8000/"

    package.json file open with a new entry of proxy and a value of http://localhost:8000/

Your code is now set up so that you can follow along with what you learned in the Moments walkthrough. There is one final difference between the Moments walkthrough setup and what you will need for this combined workspace. That is you will not need the BaseURL setting in the axiosDefaults.js file when it is created. This is because the combined workspace will receive the JSON from the API from the same URL, just on a different port (which was set with the proxy above).

So, to ensure you don’t forget this, let’s create the empty axiosDefaults.js file now and leave a comment as a reminder.

axiosDefaults.js

  1. From the root directory of your project, cd into the src folder with the following command

    cd frontend/src

  2. From inside the src folder, create a new directory called api with the following command

    mkdir api

  3. Change directory into your new api folder

    cd api

  4. From inside the api folder, create a new file called axiosDefaults.js with the following command

    touch axiosDefaults.js

  5. Move back to the root folder with the following command

    cd ../../../

    a series of commands shown in a terminal

  6. Open the axiosDefaults.js file from the file explorer, and add the following comment to it

     // IMPORTANT!!
     // Because this React app is running in the same workspace as the API,
    
     // there is no need to set a separate baseURL until you reach deployment.
    
     // Setting a baseURL before you reach deployment will cause errors
    

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

Up Next

That’s all the modifications done, so let’s get our development environment up and running.