Express Routing in MERN Stack
Last Updated :
29 Jun, 2024
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:
Folder StructureDependencies
"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:
Terminal Output
Similar Reads
Introduction to Express Prerequisite - Node.js What is Express? Express is a small framework that sits on top of Node.js's web server functionality to simplify its APIs and add helpful new features.It makes it easier to organize your application's functionality with middle ware and routing; it adds helpful utilities to Nod
2 min read
MERN Stack Interview Questions MERN Stack is one of the most well-known stacks used in web development. Each of these technologies is essential to the development of web applications, and together they form an end-to-end framework that developers can work within. MERN Stack comprises 4 technologies namely: MongoDB, Express, React
15+ min read
Monitoring and Logging in MERN Stack Monitoring and logging are crucial for maintaining the health and performance of applications. In the MERN (MongoDB, Express.js, React, Node.js) stack, these practices help in identifying issues, ensuring application stability, and providing insights into user interactions. This article will guide y
5 min read
Express.js | router.use() Function The router.use() function uses the specified middleware function or functions. It basically mounts middleware for the routes which are being served by the specific router. Syntax:router.use( path, function )Parameters:Path: It is the path to this middleware, if we can have /user, now this middleware
2 min read
Express.js express.raw() Function The express.raw() function is a built-in middleware function in Express. It parses incoming request payloads into a Buffer and is based on body-parser. Syntax:express.raw( [options] )Parameter: The options parameter contains various properties like inflate, limit, type, etc. Return Value: It returns
2 min read