In modern web development, creating a REST API to handle data interactions between a backend server and a frontend application is crucial. With React as the frontend and Node.js/Express as the backend, you can create a dynamic web application capable of fetching and sending data to the server. This tutorial will walk you through building a simple REST API with Node.js and Express and integrating it with your React application.
We’ll cover the setup of a basic Node.js backend that will handle routes and communicate with a React app to perform CRUD (Create, Read, Update, Delete) operations. By the end of this guide, you'll have a fully functioning app where the React frontend interacts with the backend through API calls.
What is Node.js and Express?
Node.js is a runtime environment that allows you to run JavaScript on the server-side, while Express is a lightweight framework built on top of Node.js for building APIs and web applications.
Install Node.js and NPM:
Initialize a New Node.js Project: Run the following command to initialize a new project:
mkdir my-node-backend
cd my-node-backend
npm init -y
Install Express: Install Express by running:
npm install express
Create a Basic Server: Create a file named server.js and set up a basic Express server:
const express = require('express');
const app = express();
const port = 5000;
app.use(express.json()); // for parsing application/json
app.get('/', (req, res) => {
res.send('Hello from the Node.js server!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Start the Server: Run the server using:
node server.js
Now, your backend server should be running at http://localhost:5000
.
What is an API Route?
An API route is where your React frontend will send HTTP requests (GET, POST, PUT, DELETE) to perform CRUD operations. These routes are defined in your Express app.
Define Basic API Routes in Express: Add routes to handle CRUD operations for a resource (e.g., users):
let users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
// GET all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// POST a new user
app.post('/api/users', (req, res) => {
const newUser = req.body;
users.push(newUser);
res.status(201).json(newUser);
});
// PUT to update a user
app.put('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const updatedUser = req.body;
const userIndex = users.findIndex(u => u.id === userId);
if (userIndex !== -1) {
users[userIndex] = { id: userId, ...updatedUser };
res.json(users[userIndex]);
} else {
res.status(404).send('User not found');
}
});
// DELETE a user
app.delete('/api/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
users = users.filter(user => user.id !== userId);
res.status(204).send();
});
What is an API Call?
An API call allows your frontend (React) to communicate with the backend server to fetch or send data.
Create a React Application: Use Create React App to initialize a new React project:
npx create-react-app my-react-frontend
cd my-react-frontend
Install Axios for HTTP Requests: Axios is a promise-based HTTP client that helps make API requests from React:
npm install axios
2. Make API Calls from React: In your React app, create components that interact with the backend API.
For example, create a UsersList component to display users fetched from the backend:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const UsersList = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
axios.get('http://localhost:5000/api/users')
.then(response => {
setUsers(response.data);
})
.catch(error => console.error('There was an error fetching the users!', error));
}, []);
return (
<div>
<h1>Users List</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
};
export default UsersList;
Run Your React App: Start the React app:
npm start
Now that you have both your frontend (React) and backend (Node.js/Express) set up, you can send data between them.
Create a Form in React to Add Users: Allow users to submit data to the backend via a form
const AddUser = () => {
const [name, setName] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const newUser = { id: Date.now(), name };
try {
await axios.post('http://localhost:5000/api/users', newUser);
alert('User added successfully!');
} catch (error) {
console.error('Error adding user:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button type="submit">Add User</button>
</form>
);
};
Post Data from React to Backend: Use Axios to send a POST request to the backend when the form is submitted. The new user will be added to the backend, and the frontend will update automatically.
Test Backend: Test the REST API directly by making requests to the backend using tools like Postman or Insomnia to verify that the routes work correctly.
Test Frontend: Make sure the React app is able to fetch data and interact with the backend. Test by adding, deleting, and updating users.
Building a REST API with Node.js and Express for a React app is an essential skill in modern web development. By creating a backend API and linking it with the frontend React application, you enable users to interact dynamically with the application. This setup allows for CRUD operations, making your app functional and interactive.
With Express handling the backend and Axios facilitating HTTP requests in React, you now have a basic full-stack application. By following the steps outlined, you can expand your app’s functionality by adding authentication, validation, or advanced data handling.