A RESTful API built with Express.js and MongoDB for managing student records. This project demonstrates fundamental Express.js concepts including routing, middleware, database integration, and CRUD operations.
- About Express.js
- Features
- Project Structure
- Prerequisites
- Installation
- Configuration
- Running the Application
- API Endpoints
- Express.js Core Concepts
- Middleware Explained
- Routing in Express
- Error Handling
- Testing with Postman/cURL
- Common Issues & Solutions
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of building server-side applications and APIs.
- Minimalist & Unopinionated: Provides the essentials without enforcing structure
- Robust Routing: Advanced routing with support for parameters, query strings, and middleware
- Middleware Support: Extensive middleware ecosystem for various functionalities
- HTTP Utilities: Simplified HTTP request/response handling
- Performance: Lightweight and fast
- Community: Large ecosystem with numerous plugins and extensions
- β RESTful API architecture
- β MongoDB database integration with Mongoose ODM
- β CRUD operations (Create, Read, Update, Delete)
- β Environment variable configuration
- β JSON request/response handling
- β Error handling middleware
- β Modular route organization
- β Auto-restart with Nodemon
Week 2/
β
βββ config/
β βββ db.js # Database connection configuration
β
βββ models/
β βββ Student.js # Mongoose schema and model for Student
β
βββ routes/
β βββ studentRoutes.js # Student-related API routes
β
βββ .env # Environment variables (not in repo)
βββ .gitignore # Git ignore file
βββ package.json # Project dependencies and scripts
βββ server.js # Main application entry point
βββ README.md # Project documentation
Before running this project, ensure you have the following installed:
- Node.js (v14 or higher) - Download
- npm (comes with Node.js) or yarn
- MongoDB (local installation or MongoDB Atlas account) - Download
- Postman (optional, for API testing) - Download
-
Clone the repository (or navigate to the project directory):
https://github.com/PLP-MERN-Stack-Development/Week2-express-JS.git
-
Install dependencies:
npm install
This will install:
express
- Web frameworkmongoose
- MongoDB ODMdotenv
- Environment variable managementnodemon
- Development server with auto-restart
-
Create a
.env
file in the root directory:touch .env
-
Add the following environment variables:
PORT=5000 MONGO_URI=mongodb://localhost:27017/studentDB
For MongoDB Atlas (cloud database):
PORT=5000 MONGO_URI=mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/studentDB?retryWrites=true&w=majority
Replace
<username>
and<password>
with your MongoDB Atlas credentials.
npm start
npm run dev
The server will start at: http://localhost:5000
You should see:
Server running on http://localhost:5000
MongoDB Connected.....
Method | Endpoint | Description | Request Body |
---|---|---|---|
GET |
/ |
Welcome message | - |
GET |
/students |
Get all students | - |
POST |
/students |
Create a new student | { "name": "John Doe", "age": 20, "email": "john@example.com" } |
PUT |
/students/:id |
Update student by ID | { "name": "Jane Doe", "age": 21, "email": "jane@example.com" } |
DELETE |
/students/:id |
Delete student by ID | - |
curl -X GET http://localhost:5000/students
curl -X POST http://localhost:5000/students \
-H "Content-Type: application/json" \
-d '{"name":"Alice Smith","age":22,"email":"alice@example.com"}'
curl -X PUT http://localhost:5000/students/6501234567890abcdef12345 \
-H "Content-Type: application/json" \
-d '{"name":"Alice Johnson","age":23}'
curl -X DELETE http://localhost:5000/students/6501234567890abcdef12345
The Express application is created using:
const express = require('express');
const app = express();
The app
object represents your Express application and provides methods for:
- Routing HTTP requests
- Configuring middleware
- Rendering HTML views
- Registering template engines
Represents the HTTP request and contains properties for:
req.body
- Request body (requiresexpress.json()
middleware)req.params
- Route parameters (e.g.,/students/:id
)req.query
- Query string parameters (e.g.,?name=John&age=20
)req.headers
- Request headersreq.method
- HTTP method (GET, POST, etc.)
Represents the HTTP response that Express sends back:
res.json()
- Send JSON responseres.send()
- Send various types of responsesres.status()
- Set HTTP status coderes.redirect()
- Redirect to another route
Express provides methods for each HTTP verb:
app.get('/', (req, res) => { /* ... */ }); // GET request
app.post('/', (req, res) => { /* ... */ }); // POST request
app.put('/', (req, res) => { /* ... */ }); // PUT request
app.delete('/', (req, res) => { /* ... */ }); // DELETE request
Middleware functions are functions that have access to the request (req
), response (res
), and the next middleware function in the application's request-response cycle.
Applied to all routes:
app.use(express.json()); // Parses incoming JSON requests
Applied to specific router instances:
app.use("/students", require("./routes/studentRoutes"));
express.json()
- Parses JSON payloadsexpress.urlencoded()
- Parses URL-encoded payloadsexpress.static()
- Serves static files
dotenv
- Loads environment variablescors
- Enables Cross-Origin Resource Sharingmorgan
- HTTP request logger
Special middleware with 4 parameters:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something went wrong!' });
});
Request β Middleware 1 β Middleware 2 β Route Handler β Response
Each middleware can:
- Execute code
- Modify request/response objects
- End the request-response cycle
- Call the next middleware using
next()
app.METHOD(PATH, HANDLER)
- METHOD: HTTP method (get, post, put, delete)
- PATH: URL path
- HANDLER: Callback function to execute
// URL: /students/123
router.get("/:id", (req, res) => {
const studentId = req.params.id; // "123"
// ... fetch student by ID
});
// URL: /students?age=20&name=John
router.get("/", (req, res) => {
const age = req.query.age; // "20"
const name = req.query.name; // "John"
// ... filter students
});
Organize routes in separate files:
// studentRoutes.js
const router = express.Router();
router.get("/", getAllStudents);
router.post("/", createStudent);
module.exports = router;
// server.js
app.use("/students", studentRoutes);
All async operations use try-catch for error handling:
router.get("/", async (req, res) => {
try {
const students = await Student.find();
res.json(students);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
- 200: OK - Successful request
- 201: Created - Resource created successfully
- 400: Bad Request - Invalid request data
- 404: Not Found - Resource not found
- 500: Internal Server Error - Server error
-
GET Request:
- Method: GET
- URL:
http://localhost:5000/students
- Click "Send"
-
POST Request:
- Method: POST
- URL:
http://localhost:5000/students
- Headers:
Content-Type: application/json
- Body (raw JSON):
{ "name": "John Doe", "age": 20, "email": "john@example.com" }
-
PUT Request:
- Method: PUT
- URL:
http://localhost:5000/students/6501234567890abcdef12345
- Headers:
Content-Type: application/json
- Body: Updated fields
-
DELETE Request:
- Method: DELETE
- URL:
http://localhost:5000/students/6501234567890abcdef12345
Error: MongooseServerSelectionError: connect ECONNREFUSED
Solutions:
- Ensure MongoDB is running locally:
sudo systemctl start mongodb
- Check
MONGO_URI
in.env
file - For Atlas, verify network access settings (allow your IP)
Error: EADDRINUSE: address already in use :::5000
Solutions:
- Change port in
.env
file - Kill process using port:
lsof -ti:5000 | xargs kill -9
Possible Causes:
- Missing
express.json()
middleware - Incorrect Content-Type header
- Route not properly defined
Solution:
app.use(express.json()); // Add this before routes
Error: Cannot find module 'express'
Solution:
npm install
Solution:
- Ensure
.env
file is in root directory - Add
require('dotenv').config()
at top ofserver.js
- Restart server after changes
- Postman - API testing
- MongoDB Compass - Database GUI
- Nodemon - Auto-restart server
Feel free to fork this project, submit issues, or create pull requests for improvements!
This project is open-source and available under the ISC License.
Created as part of the PLP MERN Stack July Cohort - Week 2 learning materials.
Happy Coding! π