Horje
Express Routing in MERN Stack

Express is a powerful framework for building web applications and APIs in NodeJS. When integrated into the MERN (MongoDB, Express, React, Node.js) stack, Express handles server-side routing and provides a robust foundation for handling HTTP requests and responses.

In this article, we will explore how to implement Express Routing in MERN Stack applications within the context of a MERN stack setup. We’ll cover the complete setup, and folder structure, and provide example code to illustrate the process.

Prerequisites

Steps To Implement Express Routing

Step 1: Initialize the Project

Create a new directory for your MERN stack project and initialize a new NodeJS project using npm.

mkdir mern-express-routing
cd mern-express-routing
npm init -y

Step 2: Install Dependencies

Install necessary packages:

npm install express mongoose body-parser cors

Step 3: Set Up Folder Structure

Create a basic folder structure for your MERN application:

ewf

Folder Structure

Dependencies

"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.19.2",
"mongoose": "^8.4.4"
}

Step 4: Create an Express Server

Inside the server directory, create server.js and set up the Express server.

JavaScript
// server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 5000;

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

// Connect to MongoDB (replace with your MongoDB connection string)
const MONGODB_URI = 'mongodb://localhost:27017/mern-express-routing';
mongoose.connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('MongoDB connected'))
    .catch(err => console.log(err));

// Routes
const todoRoutes = require('./routes');
app.use('/api/todos', todoRoutes);

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

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

// GET all todos
router.get('/', async (req, res) => {
    try {
        const todos = await Todo.find();
        res.json(todos);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});

// POST a todo
router.post('/', async (req, res) => {
    const todo = new Todo({
        title: req.body.title,
        description: req.body.description
    });

    try {
        const newTodo = await todo.save();
        res.status(201).json(newTodo);
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
});

// DELETE a todo
router.delete('/:id', async (req, res) => {
    try {
        await Todo.findByIdAndRemove(req.params.id);
        res.json({ message: 'Todo deleted' });
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});

module.exports = router;
JavaScript
//models.js

const mongoose = require('mongoose');

const todoSchema = new mongoose.Schema({
    title: { type: String, required: true },
    description: { type: String, required: true }
});

module.exports = mongoose.model('Todo', todoSchema);

Step 5: Test the Application

Run your Express server and test the routes using tools like Postman or by integrating with a frontend React application (not detailed here). Ensure that CRUD operations work as expected.

node server.js

Output:

kn

Terminal Output




Reffered: https://www.geeksforgeeks.org


Express.js

Related
Passing Data to EJS Templates Passing Data to EJS Templates
Music Playlist Manager with Node.js and Express.js Music Playlist Manager with Node.js and Express.js
Subscription Management System with NodeJS and ExpressJS Subscription Management System with NodeJS and ExpressJS
Budget Tracking App with Node.js and Express.js Budget Tracking App with Node.js and Express.js
How to Deploy ExpressJS on Netlify ? How to Deploy ExpressJS on Netlify ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16