Establishing Connection between React, Node.js, and Mongoose

Posted by


In this tutorial, we will explore how to connect React frontend with a backend server using Node.js and Mongoose to handle MongoDB database operations.

Step 1: Set up your backend server with Node.js

First, you need to set up your backend server using Node.js. Create a new folder for your backend project and run the following commands in your terminal:

mkdir backend
cd backend
npm init -y
npm install express mongoose cors dotenv

This will create a package.json file and install necessary dependencies for your backend server.

Next, create a new file called server.js in your backend folder and add the following code:

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();

const app = express();

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

// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => {
    console.log('Connected to MongoDB');
}).catch(err => console.error(err));

// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

This code sets up an Express server, connects to MongoDB using Mongoose, and starts the server listening on a specified port. Make sure to create a .env file in your backend folder with your MongoDB connection string like this:

MONGODB_URI=mongodb://localhost/mydatabase

Step 2: Set up your React frontend

Create a new folder for your frontend project and run the following commands in your terminal:

npx create-react-app frontend
cd frontend

This will set up a new React project with all necessary files and dependencies installed.

Step 3: Make API calls from React to Node.js backend

Create a new file called api.js in your frontend/src folder and add the following code:

const API_URL = 'http://localhost:5000/api';

export const fetchData = async () => {
    try {
        const response = await fetch(`${API_URL}/data`);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error(error);
    }
};

In this code, we define a function fetchData that makes a GET request to our backend server to fetch data.

Step 4: Initializing Mongoose models in Node.js backend

Create a new folder called models in your backend folder and create a new file called Data.js. In this file, define your MongoDB schema like this:

const mongoose = require('mongoose');

const dataSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    age: {
        type: Number,
        required: true,
    },
});

module.exports = mongoose.model('Data', dataSchema);

This code defines a Mongoose model for storing data with a name and age field.

Step 5: Implementing API routes in Node.js backend

Create a new folder called routes in your backend folder and create a new file called dataRoutes.js. In this file, define API routes to handle CRUD operations for your data model like this:

const express = require('express');
const router = express.Router();
const Data = require('../models/Data');

// Get all data
router.get('/data', async (req, res) => {
    try {
        const data = await Data.find();
        res.json(data);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server Error' });
    }
});

module.exports = router;

Step 6: Import API routes in Node.js backend

In your server.js file, import and use your API routes like this:

const dataRoutes = require('./routes/dataRoutes');
app.use('/api', dataRoutes);

Step 7: Display data in React frontend

In your React component where you want to display the data, import fetchData function from api.js and use it like this:

import React, { useEffect, useState } from 'react';
import { fetchData } from './api';

const MyComponent = () => {
    const [data, setData] = useState([]);

    useEffect(() => {
        const getData = async () => {
            const result = await fetchData();
            setData(result);
        };

        getData();
    }, []);

    return (
        <div>
            {data.map(item => (
                <div key={item._id}>
                    <p>{item.name}</p>
                    <p>{item.age}</p>
                </div>
            ))}
        </div>
    );
};

export default MyComponent;

This code fetches data from the backend server using the fetchData function and displays it in the component.

That’s it! You have successfully connected your React frontend with a Node.js backend using Mongoose for MongoDB database operations. Feel free to expand and customize this setup for your own projects.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jenisejoseph604
3 months ago

Informative 😊