Connecting React Frontend to Express Backend

On Day 7 of my full-stack development journey, I learned how to connect a React frontend to an Express backend. This step is critical for creating full-stack applications where the client-side and server-side work seamlessly together. Here's what I learned, along with practical mini-examples for clarity.

1. Set Up Your Backend with Express

1.1 Initialize the Backend Project

  1. Open the terminal in VS Code.
  2. Navigate to your project directory or create a new folder for the backend:
mkdir backend  
cd backend

3. Initialize the project and install dependencies:

npm init -y
npm install express cors

1.2 Write the Backend Code
1. Create a file named server.js in the backend folder.

  1. Add the following code to create an Express server
const express = require('express');
const cors = require('cors');
const app = express();

// Enable CORS
app.use(cors());

// Mock data
const products = [
  { id: 1, name: 'Product 1', price: 100 },
  { id: 2, name: 'Product 2', price: 200 },
];

// API route
app.get('/api/products', (req, res) => {
  res.json(products);
});

// Start the server
app.listen(5000, () => {
  console.log('Server running on http://localhost:5000');
});

1.3 Run the Backend Server
1. In the terminal, start the server
2.Verify the server is running by visiting http://localhost:5000/api/products in your browser. You should see the mock data in JSON format.

node server.js

2. Set Up Your React Frontend

2.1 Initialize the React Project
1. Open a new terminal tab in VS Code (or use a separate terminal window).
2. Navigate to your project directory or create a new folder for the frontend.
3. Create a React app:

npx create-react-app .

2.2 Install Axios

npm install axios

2.3 Fetch Data from Backend
1. Open the App.js file in your React project.
2. In React, we use the map() method to iterate through this array and render each product. Here’s an example of mapping.
3. Replace its content with this code to fetch data from the backend and display it.

import React, { useEffect, useState } from 'react';  
import axios from 'axios';

const App = () => {  
  const [products, setProducts] = useState([]);

  // Fetch data from the backend when the component mounts  
  useEffect(() => {  
    axios.get('/api/products') // Use proxy for backend URL  
      .then((response) => setProducts(response.data))  
      .catch((error) => console.error('Error fetching data:', error));  
  }, []);

  return (  
    <div>  
      <h1>Product List</h1>  
      <ul>  
        {products.map((product) => (  
          <li key={product.id}>  
            {product.name} - ${product.price}  
          </li>  
        ))}  
      </ul>  
    </div>  
  );  
};

export default App;

2.4 Start the React App

npm start

3. Configure Proxy for Backend Requests

  1. Open the package.json file in your React project.

  2. Add the following line
    "proxy": "localhost:5000"