Setting Up Express
npm init -y
npm install express
// server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.json({ message: 'Welcome to the API' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Route Parameters and Query Strings
// GET /api/users/:id
app.get('/api/users/:id', (req, res) => {
const { id } = req.params;
res.json({ id, name: 'Alice' });
});
// GET /api/users?page=1&limit=10
app.get('/api/users', (req, res) => {
const { page = 1, limit = 10 } = req.query;
res.json({ page: Number(page), limit: Number(limit) });
});
Middleware
// Request logging middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
next();
});
// CORS middleware
const cors = require('cors');
app.use(cors());
Error Handling
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
// Global error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({ error: err.message });
});
Ready to Level Up Your Coding Skills?
Join Coderz Club and learn to code with challenges, battles, and an AI mentor.
Join Coderz Club Free →