How to Create a React Frontend, Express Backend and Connect Them Together

Express Nodejs ReactLeave a Comment on How to Create a React Frontend, Express Backend and Connect Them Together

How to Create a React Frontend, Express Backend and Connect Them Together

 

Express is a popular unopinionated web framework, written in JavaScript and hosted within the Node.js runtime environment. It is also a modern backend technology and popular among new developers.

React, a simple and powerful library is gaining huge popularity among developers nowadays. The component architecture is making react an easier way of making the complicated web application UIs in record time. Also, the maintenance and bug fixes are simpler because the codes are divided into components.

Before continuing this tutorial, I am assuming that you learned JavaScript and aware of React, and Nodejs/Express. If you’ve just started with React, it’s recommended that you’d start with creating a basic todo list application or an attendance management app that’ll help you get started with React concepts.

Here we are going to make a simple React application and connect it to Nodejs/Express backend.

Creating a Node/Express Backend

First, we need to create a Backend to take requests from frontend and to serve responses.

Install and Set Up Nodejs

Installing Nodejs on our system may differ with our Operating System.

For MacOS and Windows users, the below link can be referred to download the Nodejs Installation file.

https://nodejs.org/en/download/

For Ubuntu users, Nodejs can be installed with the below commands.

curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs

For other operating systems, the installation instructions are available with the link below.

https://nodejs.org/en/download/package-manager/

Install Nodemon

Nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

npm i -g nodemon

Create a Project Directory

Create a project directory and navigate to it using our Command Prompt/Terminal.

mkdir express-backend
cd express-backend

Initialize NPM

It requires a package.json file inside our project directory to work with NPM. So we need to initialize NPM.

npm init

Install Express

Now inside our project, we need to install Express package.

npm i express --save

Install Cors

CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

npm i cors --save

Install Body-Parser

To handle HTTP POST request in Express.js version 4 and above, we need to install the middleware module called body-parser. When we don’t use it, we get the raw request, and your body and headers are not in the root object of the request parameter.

npm i body-parser --save

Install Morgan

Morgan is basically a logger, on any requests being made, it generates logs automatically.

npm i morgan --save

Configure the Root File (index.js)

When initializing NPM, we selected index.js as our entry point(root file). So the app directs to index.js first and so we need to create and configure it.

Create index.js

We can create a file named index.js in our project directory using GUI or using our terminal.

touch index.js
Import all packages installed

Import all the packages we have installed earlier to our index.js file.

const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
Define port number

Now define a port number in which our app needs to be started.

const port = process.env.PORT || 3001;
Use Logger

Use the logger package we have imported to get the log details of our application if needed.

app.use(logger('dev'));
Use Cors

Now use cors to enable Cross-Origin Resource Sharing.

app.use(cors());
Use Body-Parser

Also, use body-parser to handle HTTP POST requests.

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Import and use players route

Yes. We did not create a route yet. But in the future steps, it will be made and configure. So just add the below lines in our root file.

const playersRouter = require("./routes/players");
app.use("/players", playersRouter);
Listen to the port we defined

We already defined a port number and it needs to be used when starting our project. So this port number must listen to our application.

app.listen(port, function() {
  console.log("Runnning on " + port);
});
Export the app module.

Now export the module app we created.

module.exports = app;

Create a dummy database

Some data needs to sent to the frontend with a GET request. So it needs to create a dummy database. So first create a file named dummyDatabase.js, enter some data and export it.

touch dummyDatabase.js
let players = [
  { _id: 1, name: "Sachin", runs: "18426" },
  { _id: 2, name: "Dhoni", runs: "10500" },
  { _id: 3, name: "Virat", runs: "10843" }
];
module.exports = players;

Create a Route

We need to create a route file where all the functions of a route are defined. Here we need a list of names to our frontend and so we are going to make a names.js route inside a directory named routes.

mkdir routes
cd routes
touch players.js
Define router

Import express package and put express.Router() in a variable called router.

const express = require("express");
const router = express.Router();
Import dummy database

Now import the dummy database file we have created earlier.

let players = require("../dummyDatabase");
GET the list of players

We need to complete list of players in our database with a GET request. So we need to create a router for GET request to /list.

router.get("/list", async (req, res) => {
  try {
    res.status(200).json({
      data: players
    });
  } catch (err) {
    res.status(400).json({
      message: "Some error occured",
      err
    });
  }
});

So, the below link returns the complete list of players

 http://localhost:3001/players/list
GET a single player details

We got the full player list. Now we need each player details. This can be done by passing the id of each player as the API parameter from the frontend.

:id is id passed as the URL parameter. This value is compared with the ids in the database.

Note: The id that we are passing from frontend can be accessed from here as req.params.id and it needs to convert to the number type before comparing with database _id because the _ids in the database are in the form of numbers.

router.get("/:id", async (req, res) => {
  let { id } = req.params;
  id = Number(id);
  try {
    let player = players.find(player => player._id === id);
    res.status(200).json({
      data: player
    });
  } catch (err) {
    res.status(400).json({
      message: "Some error occured",
      err
    });
  }
});

So, the below link returns the details of player 3.

 http://localhost:3001/players/3
Export the module

Now export the router module we created.

module.exports = router;

Running our Backend

So we have created a RESTful API using Nodejs and Express. Now we can run our backend using Nodemon. Nodemon can watch the changes we are adding to our project and update the live server itself.

nodemon node index.js

Testing the APIs

So our server is running on port 3001. The recommended method of testing our APIs is with Postman and it can be downloaded using the link below.

https://www.getpostman.com/downloads/

Here our backend only dealing with GET requests without headers. So we can simply test it within our browser.

GET the complete list of players

The API URL below will show the complete list of players as JSON.

http://localhost:3001/players/list

This will return the data of players from our Express backend without a specific format. I am using the JSON formatter extension in my chrome browser to format the JSON data.

GET single player details

To get the details of a single player, we need to pass the id with our API URL. So the below URL will return the single player( _id: 2) details.

http://localhost:3001/players/list/2

Creating a React Application(Frontend)

Now it’s time to create our React application.

Install and Set Up React

We have already installed Nodejs. So we can create a React application using NPX easily.

npx create-react-app react-frontend

If it hit with any errors, refer the detailed guides.

Adding Bootstrap CDN(optional)

This is an optional step for styling our React application by adding Bootstrap CDN to the index.html file inside /public directory.

Under index.html file, we we have to add the below CDN between <header></header> section.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/>

Configure app.js

Now our working area is under /src directory. We can see a file named app.js inside it. First of all, Clear all the contents to in it so that we can code from line 0.

Import React and Component

At first, we need to import React and Component from react package.

import React, { Component } from "react";
Create a class named app and export it

We need to create a class named App and export it. All the activities from now has to be done inside this class.

export default class App extends Component {

}
Initialize all the states inside the constructor

So it needs some states to store the data from backend and to handle the UI operations.

list: if the state list is true, the list of players component will be displayed.

card: if the state card is true, the single player card will be displayed.

players: this state stores the list array of players from the backend.

player: this stores a single player detail from the backend.

constructor(props) {
    super();
    this.state = {
      list: true,
      card: false,
      players: [],
      player: {}
    };
}
Fetch the list of players from API, and store in the state

Now we need to fetch the list of players from the API URL and store it in the state players. These operations need to be done only once and so it is added inside componentDidMound().

componentDidMount() {
  fetch("http://localhost:3001/players/list")
  .then(response => response.json())
  .then( responseJson=> {
    this.setState({ players:responseJson.data });
  },
)}
Create a function to handle the view of a single player card

Now we need to create a function showCard() which handles the view of single player detail card. Inside this, it needs to fetch each player detail with the id and store it in a state named player.

This function can also be used for UI functions. Here we make list value false and card value true. This will hide players list view and show single player card view.

showCard=id=> {
  fetch(`http://localhost:3001/players/${id}`)
  .then(response => response.json())
  .then(
  responseJson=> {this.setState({ player:responseJson.data })},
);
this.setState({
  list:false,
  card:true
});
};
Create a function to handle the view of players list

We have a Back button in card view and pressing it will call a function named showList() where it makes card value false and list value true. This will show players list view and hide single player card view.

showList = () => {
   this.setState({
     card: false,
     list: true
   });
};
Start Render function and return

Now we can start the render() function and return our views.

render(){
return(
<div className ="container">

</div>
)
}

This will show up a blank page in our browser window if the project is started.

So, before starting our react application, we need to add two UI components. The list view and the card view.

Set up the list view to show players list

Show this list view only if the state list if true. In this situation, map through the array stored in the state players and show each player name inside the map function. Also, when clicking each name, there have to execute the function showCard(). We have to pass the player id with this function because the data needs to be fetched from backed and shown in the card.

        {this.state.list ? (
          <div className="list-group">
            {this.state.players.map(player => (
              <li
                onClick={() => this.showCard(player._id)}
                className="list-group-item list-group-item-action"
              >
                {player.name}
              </li>
            ))}
          </div>
        ) : null}
Set up the card view to show a player detail

Show this card view only if the state card is true. In this situation, show details in state player.

        {this.state.card ? (
          <div class="card" style={{ width: "18rem" }}>
            <div class="card-body">
              <h5 class="card-title">{this.state.player.name}</h5>
              <p class="card-text">{this.state.player.runs}</p>
              <div onClick={() => this.showList()} class="btn btn-primary">
                Back
              </div>
            </div>
          </div>
        ) : null}

Running our Frontend

We also created a frontend in React successfully and now it can be started using the following command.

npm start

This will open up our application in port 3000 and can be accessed with the below URL.

http://localhost:3000

GitHub

The complete project here I made is uploaded in GitHub for reference.

Backend
https://github.com/syamjayaraj/SimpleExpressBackend
Frontend
https://github.com/syamjayaraj/SimpleReactFrontend

Have a nice code!

Hi, I'm Syamlal, the co-founder of Redmonark. I'm a developer, writer and also have a little bit of experience in graphic designing.
Website https://syam.me

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top