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.
PrerequisitesSteps To Implement Express RoutingStep 1: Initialize the ProjectCreate 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 DependenciesInstall necessary packages:
npm install express mongoose body-parser cors Step 3: Set Up Folder StructureCreate a basic folder structure for your MERN application:
 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 ServerInside 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 ApplicationRun 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: Terminal Output
|