blogpost_cover

Set Up Create React App with Express

When I first reached the full stack JavaScript applications on Free Code Camp, I searched, read articles and thought how I would start a full stack JavaScript application. I tried using Clementine.js but I don’t really understand that time why there are so many folders, the project directory and the example application itself.

So, today. Just accept that if you want to build a full stack JS app, you need a client and a server. And for this article, we’re going to use React for our client and Express for our server. Then, we need to connect them and make them talk to each other. And I expect you guys to have Node.js installed and a code editor (I prefer Visual Studio Code because there’s a terminal embedded in it).

        1. Create a folder.
        2. Open VS Code (or your code editor you prefer) and open your folder in the editor.
        3. If the terminal does not appear in VS Code, enter ‘Ctrl + `’. (Ctrl + tilde)
          vscode_terminal
        4. To create a project using npm, let’s enter this command in the terminal.
          npm init
        5. Just enter your answers to the items like your name as an author of the app or a description of your app. If you don’t understand few terms, just let it be and enter until it asks you to enter yes.command1You can see these properties in the file, “package.json”.
        6. If you just entered (index.js) as your entry point in our npm init command, create index.js  in the root directory where we will put our server code. If you changed it when we initialized it (for ex., server.js), then create a file with that file name in your root directory.
        7. Install Express as a dependency in your terminal.
          npm i -S express
          

          This means you install express module as a dependency. It needs express to successfully run your application.

        8. Add this code to your index.js file.
          const express = require('express');
          const path = require('path');
          const app = express();
          app.use(express.static(path.join(__dirname, 'client/public')));
          app.get("/testApi/user", (req, res) => {
          return res.json({"user":"Eirin Gonzales", "bio":"I'm a front end engineer."});
          });
          app.listen(3001, function() {
          console.log("Working");
          });

          You can put your own name and your own bio.

        9. Install nodemon as a global command. When we install a module as a global command, it means we can use the module’s name as a command in our terminal.
          npm i -g nodemon

          Nodemon automatically restarts our project when we have code changes. We will use this command when we run our server code.

        10. Install create react app as a global command.
          npm i -g create-react-app
          create-react-app client

          The module, create-react-app, is a build setup with no configuration. We will use this so we can easily create single-page React applications. CRA does the configuration for us. It generates a client folder where our files will be stored.

        11. In your terminal, go inside client folder.
          cd client

          Run this command.

          npm start

          It’ll open a page in your browser and you can see a page with React logo and few content.

        12. Open another terminal. And just inside your root folder, run
          nodemon
        13. You can also see App.js file inside client/src folder. Open it. And add this code inside App class but before the render method.
            constructor(props) {
              super(props);
          
              this.state = {
                name: "",
                bio: ""
              };
          
              this.set = this.set.bind(this);
            }
          
            set(user) {
              this.setState({
                name: user.user,
                bio: user.bio
              });
            }
          
            componentDidMount() {
              fetch("/testApi/user")
              .then(res => res.json())
              .then(json => this.set(json))
              .catch(err => console.log(err));
            }
          

          Inside render method, add these code inside the return statement, just before the image tag.

          {this.state.name !== ""
          
          <div>
          
          <h1>Hi! My name is {this.state.name}. {this.state.bio}</h1>
          
          </div>
          
          }

          What happens here is that when this component is rendered to the browser, it should run the statement inside componentDidMount function. It’ll send a request to the url we put there and we will receive a JSON object containing a name and a bio.

          Then, we should see a name and a bio in our page. (Make sure nodemon is running in the root folder and npm start is running in your client folder in your terminals.)

        14. Have you seen your name and your bio? And you should not. Why? Because we haven’t settled the connection between our client and server.Add this in the package.json of your client folder. Add a comma after the browserslist property. Then, add it after the comma. Or you can add it after any property but it should be inside the curly braces of the JSON.
          "proxy":"http://localhost:3001/"
          

          What this does it it forwards all requests from our client (running in port 3000) to our Express server which is running in port 3001. The port 3001 in the “proxy” property must match the port of our Express server.

          app.listen(3001, function() {
          console.log("Working");
          });

          In the code above, 3001 is the port where your Express server is running on.

          So when we request “testApi/user” in our fetch from our App component, it will be forwarded to the port specified in our “proxy”.

      1. Don’t forget to save your files.

        15. Refresh the page in your browser. (Check if both terminals are running.) You should now be able to see your name and your bio.

      2. result

 

So, that’s it. I hope you learned a thing or two from this article.

If you have any questions or clarifications, just comment it below.

And if you want the files I created, you can find it here on my GitHub Repo: https://github.com/theproactivedev/cra-with-express

 

 

Have a great day! Thanks for reading this! 😀

Little Disclaimer: I’m not an expert developer yet. I just want to share the things I learned when I built my full stack JS applications.

Leave a comment