Connect Node with React



Node.js and ReactJS each tech stack are popularly utilized in modern-day full-stack web programs. ReactJS is used for the front stop and Node.js is used for the again quit.

  • ReactJS is a famous JavaScript library for building user interfaces (UIs). React main objective to simplify the intricate method of building interactive consumer interfaces.
  • Node.js is an open-supply, cross-platform JavaScript runtime environment. It is ideal for handling fast and scalable servers that can handle simultaneous connections with high throughput.

Connect Backend to Frontend

Before connecting the backend and frontend we need to create codes and directories for both so we can check the connectivity.

Steps for the Backend Directory

Step 1: First, create and Go to the backend directory by the following command in the terminal.

mkdir backend
cd backend

Step 2: Initialize it with index.js as an entry point.

npm init

Sometimes can be named app.js then we have to use app.js as an entry point.

Step 3: Install the required libraries.

npm i express nodemon

Nodemon basically helps developers build Node.js applications by automatically restarting the application when it detects changes to files in the directory.

After installing the nodemon, its version should be reflected in package.json file like this.

"express": "^4.19.2",
"nodemon": "^3.1.4"

Steps for Frontend Directory

Step 1: In the first step, create a react app named by using the following command.

npx create-react-app frontendReact

Step 2: Get into the project directory by following the command.

cd frontendReact

Project Structure

After that, the project structure will look like this.

Apart from this we also need to install some other dependencies by using the following command

npm install express body-parser cors

Connecting Node.js and ReactJS

Before connecting backend and frondent we have to write codes for both end in Node.js and ReactJS.

Backend Example Code

Here I am taking a simple example for the backend server.

// File path-> backend/index.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = 3000;

// Middleware
app.use(cors());
app.use(bodyParser.json());

// POST route
app.post('/api/message', (req, res) => {
  const { message } = req.body;
  console.log('Received message:', message);
  res.json({ reply: `Server received: ${message}` });
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Run the backend server by using the following command

npm run dev

Output

After Running this command output should be like this.

In this step, we are going to connect the backend server to the frontend by adding a proxy in the package.json file of the react folder which should be like this.

"proxy": "http://localhost:3000"

This tells React to proxy API requests to the Node.js server built with Express in our project.

Frontend Example Code

This code lets in the user to input a message, sends this message to the backend via a POST request, and then shows the server's reaction. It makes use of React's kingdom control to handle the enter, shape submission, and show of the server's respond.

// File path-> frontend/app.js

import React, { useState } from 'react';

function App() {
  const [message, setMessage] = useState('');
  const [reply, setReply] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    fetch('http://localhost:3000/api/message', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ message }),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log('Reply from server:', data);
        setReply(data.reply);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
        />
        <button type="submit">Send Message</button>
      </form>
      <p>Server Reply: {reply}</p>
    </div>
  );
}

export default App;

To run the following code type the following command in the terminal

npm start

Output

After running both the frontend and the backend server we can see that the message we are typing in and sending in the frontend is received in the backend terminal.

Updated on: 2024-08-19T11:13:08+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements