Define endpoints, set responses, and generate a complete Express.js mock server.
const express = require("express"); const cors = require("cors"); const app = express(); const PORT = process.env.PORT || 3001; // Middleware app.use(cors()); app.use(express.json()); // Request logger app.use((req, res, next) => { console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`); next(); }); // --- Endpoints --- app.get("/api/users", (req, res) => { res.status(200).json([ { "id": 1, "name": "Alice Chen", "email": "alice@example.com" }, { "id": 2, "name": "Bob Martinez", "email": "bob@example.com" } ]); }); app.get("/api/users/:id", (req, res) => { res.status(200).json({ "id": 1, "name": "Alice Chen", "email": "alice@example.com", "role": "admin" }); }); app.post("/api/users", (req, res) => { res.status(201).json({ "id": 3, "name": "New User", "email": "new@example.com" }); }); // 404 handler app.use((req, res) => { res.status(404).json({ error: "Not Found", message: `No mock defined for ${req.method} ${req.path}`, availableEndpoints: [ "GET /api/users", "GET /api/users/:id", "POST /api/users", ], }); }); app.listen(PORT, () => { console.log(`Mock server running at http://localhost:${PORT}`); console.log("Available endpoints:"); console.log(` GET http://localhost:${PORT}/api/users`); console.log(` GET http://localhost:${PORT}/api/users/:id`); console.log(` POST http://localhost:${PORT}/api/users`); });
# Initialize and install dependencies npm init -y npm install express cors # Run the mock server node server.js # Test an endpoint curl http://localhost:3001/api/users

New tutorials, open-source projects, and deep dives on coding agents - delivered weekly.