5-developing-a-full-stack-app-with-react-expressjs-and-mongodb.html

Developing a Full-Stack App with React, Express.js, and MongoDB

In the ever-evolving landscape of web development, building a full-stack application can seem daunting. However, with the right tools and frameworks, it becomes an achievable and rewarding endeavor. This article will guide you through the process of developing a full-stack application using React for the front end, Express.js for the back end, and MongoDB as your database. With clear code examples, actionable insights, and step-by-step instructions, you’ll be well-equipped to create a robust application.

What is a Full-Stack Application?

A full-stack application encompasses both the front end (client-side) and back end (server-side) of a web application. The front end is what users interact with directly, while the back end handles data storage, business logic, and server-side operations. The combination of React, Express.js, and MongoDB is popular because:

  • React allows for dynamic user interfaces.
  • Express.js provides a flexible Node.js framework for building APIs.
  • MongoDB offers a powerful NoSQL database for storing data in JSON-like format.

Setting Up Your Development Environment

Before diving into coding, ensure you have the necessary tools installed:

  1. Node.js: Download and install Node.js from nodejs.org.
  2. MongoDB: Set up a local MongoDB instance or create a free account on MongoDB Atlas.
  3. Code Editor: Use a code editor such as Visual Studio Code for a seamless coding experience.

Step 1: Initialize the Project

Create a new directory for your project and initialize a Node.js application:

mkdir fullstack-app
cd fullstack-app
npm init -y

Step 2: Install Required Packages

For the backend, you’ll need Express.js and Mongoose (an ODM for MongoDB):

npm install express mongoose cors dotenv

For the front end, we’ll use Create React App:

npx create-react-app client

Step 3: Set Up the Backend

Create the Server

In the root directory, create a file named server.js:

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

const app = express();
const PORT = process.env.PORT || 5000;

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

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

// Define a simple route
app.get('/', (req, res) => {
    res.send('API running');
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Create a Model

Create a new directory called models, and inside it, create a file named Item.js:

const mongoose = require('mongoose');

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

module.exports = mongoose.model('Item', ItemSchema);

Create Routes

Create a new directory named routes and a file named items.js inside it:

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

// Get all items
router.get('/', async (req, res) => {
    const items = await Item.find();
    res.json(items);
});

// Create an item
router.post('/', async (req, res) => {
    const newItem = new Item(req.body);
    await newItem.save();
    res.json(newItem);
});

module.exports = router;

In your server.js, import and use the new routes:

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

Step 4: Set Up the Frontend

Navigate to the client directory and open src/App.js. Replace its contents with the following:

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

function App() {
    const [items, setItems] = useState([]);
    const [name, setName] = useState('');
    const [quantity, setQuantity] = useState(0);

    useEffect(() => {
        fetch('http://localhost:5000/api/items')
            .then(response => response.json())
            .then(data => setItems(data));
    }, []);

    const addItem = async () => {
        const response = await fetch('http://localhost:5000/api/items', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name, quantity }),
        });
        const newItem = await response.json();
        setItems([...items, newItem]);
        setName('');
        setQuantity(0);
    };

    return (
        <div>
            <h1>Item List</h1>
            <input value={name} onChange={e => setName(e.target.value)} placeholder="Item Name" />
            <input type="number" value={quantity} onChange={e => setQuantity(e.target.value)} placeholder="Quantity" />
            <button onClick={addItem}>Add Item</button>
            <ul>
                {items.map(item => (
                    <li key={item._id}>{item.name}: {item.quantity}</li>
                ))}
            </ul>
        </div>
    );
}

export default App;

Step 5: Run Your Application

  1. Start your backend server:
node server.js
  1. Open a new terminal, navigate to the client directory, and start the React app:
npm start

Now, you should see your full-stack application in action at http://localhost:3000. You can add items, which will be saved in your MongoDB database.

Troubleshooting Tips

  • CORS Issues: If you encounter CORS-related errors, ensure you have included the cors middleware in your Express app.
  • Database Connection: Double-check your MongoDB connection string in the .env file.
  • Port Conflicts: Make sure the backend and frontend are running on different ports (5000 for Express, 3000 for React).

Conclusion

Developing a full-stack application using React, Express.js, and MongoDB can significantly enhance your web development skills. By following the structured approach outlined in this article, you've learned to set up a basic full-stack application, enabling you to expand and customize it to meet your specific needs. Keep experimenting and exploring the vast possibilities these technologies offer, and you’ll be on your way to becoming a proficient full-stack developer. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.