Node React Tutorial – How to connect React with backend Node.js?

Node React Tutorial – How to connect React with backend Node.js?

In this tutorial, we will learn how to connect React with backend Node.js. We will use Express.js as a backend framework.

Before moving ahead, let’s understand what Frontend and Backend are.

What is Frontend?

In very simple words, the front end is the interface that the user sees and interacts with. Most of the technologies that are used for front-end development are HTML, CSS, and JavaScript. It is also known as the client side.

To make the frontend development easier, we use frameworks like React, Angular, Vue, etc. In today’s article, we will use React. You can get started with React for free on codedamn through a free React course.

If you want to pursue a career in frontend development, take a look at this blog post: How To Become Frontend Developer: Step-by-Step Guide In 2022.

What is Backend?

Backend development is the process of creating the server side of the application. It mainly handles the data and logic of the application. Technologies like Express.js, Python, Java, PHP, etc. are used for backend development.

In today’s article, we will use Express.js which is a back-end web application framework for Node.js.

How do the front end and back end work together?

There are various ways to connect the front end with the back end. In this tutorial, we will expose an API (Application Programming Interface) endpoint from the backend and use it in the front end. That’s how our backend and front end will work together.

Prerequisites

You need to have Node.js installed on your system.

The easiest way to install Node.js is to use Node Version Manager. It is a bash script that allows you to install, update, and switch between different versions of Node.js.

Once you have installed nvm, you can install the latest version of Node.js by running the following command:

nvm install nodeCode language: Bash (bash)

You can check the version of Node.js by running the following command:

node -vCode language: Bash (bash)

Installing Node.js will also install npm (Node Package Manager) on your system. You can check the version of npm by running the following command:

npm -vCode language: Bash (bash)
Install Node.js and check versions of node and npm
Install Node.js and check versions of node and npm

Project Setup

We will put the frontend code in the client folder and the backend code in the server folder. We will use create-react-app to create the front-end application.

Step 1. Building the frontend React application

First, we will create a React application. Open your terminal and run the following command to create a React application.

npx create-react-app clientCode language: Bash (bash)

If it says something like this:

Need to install the following packages:
  [email protected]
Ok to proceed? (y) yCode language: Bash (bash)

Then press y and hit enter.

This command will create a React app with boilerplate code in the client folder.

After react app is created
After react app is created

To run the React application, open your terminal and run the following command.

cd client
npm startCode language: Bash (bash)

This command will start the React application on port 3000.

React app started on port 3000
React app started on port 3000

Open your browser and visit http://localhost:3000/ where you will see the React application running like this:

React app in browser
React app in the browser

Now that we have the frontend application running, let’s create the backend application.

Step 2: Building the Backend Node.js server

Installing the dependencies

Open a new terminal and create a new directory called server and initialize a Node.js project in it.

mkdir server
cd server
npm init -yCode language: Bash (bash)

Note: We are using npm init -y to initialize the project without any prompts. If you want to initialize the project with prompts, you can use npm init. You can read more about npm init here.

Let’s install the required dependencies for our application.

npm install express corsCode language: Bash (bash)

For development purposes, we will install nodemon as a development dependency.

npm install nodemon --save-devCode language: Bash (bash)
Install server dependencies
Install server dependencies

So we installed:

  1. express – The web application framework for Node.js that we will use to create the backend application.
  2. cors – CORS (Cross-Origin Resource Sharing) is a browser security feature that restricts cross-origin HTTP requests with other servers and specifies which domains access your resources. We will use this Node.js package to allow cross-origin requests.
  3. nodemon – A utility that will monitor for any changes in your source and automatically restart your server if any changes are detected.

Lastly, we will add a start script in the package.json file to start the server.

"scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
}Code language: YAML (yaml)

At this point, we have all the dependencies installed and the dev and start script added in the package.json file. Without further ado, let’s create the server.

Creating the server

Start with creating a new file named server.js in the server folder.

1. Import express and cors
const express = require('express');
const cors = require('cors');Code language: JavaScript (javascript)

Here, require() is a built-in function to include external modules in your Node.js application using which we are importing the express and cors modules.

2. Create an Express application
const app = express();

app.use(cors());
app.use(express.json());Code language: JavaScript (javascript)

The express() function is a top-level function exported by the express module and it can be used to create an Express application.

We are using cors to allow cross-origin requests. We are using app.use() to add the cors middleware to the Express application.

To parse the incoming requests with JSON payloads we are using express.json() which is a built-in middleware function in Express.

3 . Create a GET route
app.get('/message', (req, res) => {
    res.json({ message: "Hello from server!" });
});Code language: JavaScript (javascript)

Now, we will create an endpoint /message that will return a JSON object with the message Hello from server!. We are using app.get() to create a GET route. It takes two arguments:

  1. The path of the endpoint which in our case is just /message.
  2. The callback which can be a middleware function or a series/array of middleware functions.

Since we are returning a JSON object, we are using res.json() to send a JSON response.

NOTE: GET is one of the HTTP methods. You can read more about HTTP methods here.

4. Start the server
app.listen(8000, () => {
  console.log(`Server is running on port 8000.`);
});Code language: JavaScript (javascript)

To start the server we will use app.listen() which takes two arguments:

  1. The port number on which the server will run. In our case, it is 8000.
  2. A callback function will be called when the server starts which in our case will just log the message that the server is running.

The final server.js file will look like this:

const express = require("express");
const cors = require("cors");
const app = express();

app.use(cors());
app.use(express.json());

app.get("/message", (req, res) => {
  res.json({ message: "Hello from server!" });
});

app.listen(8000, () => {
  console.log(`Server is running on port 8000.`);
});Code language: JavaScript (javascript)

To start the backend server open your terminal and run the following command:

npm run devCode language: Bash (bash)

This command will start the server on port 8000.

Start server on port 8000
Start server on port 8000

To check if the server is working, open your browser and go to http://localhost:8000/message where you will see the JSON object returned by the server.

/message endpoint in browser
/message endpoint in a browser

At this point we have our server running on port 8000, and our frontend application running on port 3000. We will now connect the frontend application to the backend application.

Step 3: Connect React with Node.js

Open the App.js file in the src folder and then replace the code with the following code.

import React, { useState, useEffect } from "react";
import "./App.css";

function App() {
  const [message, setMessage] = useState("");

  useEffect(() => {
    fetch("http://localhost:8000/message")
      .then((res) => res.json())
      .then((data) => setMessage(data.message));
  }, []);

  return (
    <div className="App">
      <h1>{message}</h1>
    </div>
  );
}

export default AppCode language: JavaScript (javascript)

Let’s go through the code.

First, we are importing useState and useEffect from the react module. We are using useState to create a state variable message and useEffect to call the API when the component mounts.

Inside the useEffect hook, we are calling the API using fetch() and setting the response to the message state variable. To read more about fetch() visit the Mozilla docs here.

Note that we have passed an empty array as the second argument to the useEffect hook i.e the deps the parameter which will make sure that the useEffect hook is called only once when the component mounts.

Now, we are rendering the message state variable in the h1 tag.

Open your browser and visit http://localhost:3000/ where you will see the message “Hello from server!” on the screen.

Final react app connected with the backend
The final react app connected with the backend

Here is the overview of the project structure.

Project Overview
Project Overview

Conclusion

This tutorial taught us how to connect React with backend Node.js. We have created a simple React application and connected it with backend Node.js. We have used Express.js as a backend framework.

References

Sharing is caring

Did you like what Arnab Sen wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far