What is Routing?
- Routing in Express is the process of defining URL paths and associating them with HTTP request methods (GET, POST, PUT, DELETE, etc.) and controller functions.
- Each route tells Express what to do when a specific URL is hit.
Example Routing
// routes/userRoutes.js
const express = require("express");
const router = express.Router();
const userController = require("../controllers/userController");
router.get("/users", userController.getAllUsers);
router.post("/users", userController.createUser);
module.exports = router;
router.get()
→ Handles GET requests
router.post()
→ Handles POST requests
- Connects routes to the respective controller functions.
Integrating Routes in Main App
const express = require("express");
const app = express();
const userRoutes = require("./routes/userRoutes");
app.use(express.json());
app.use("/api", userRoutes);
app.listen(3000, () => {
console.log("Server running on port 3000");
});
app.use("/api", userRoutes)
— Prefixes all user routes with /api
Key Points
- Controllers handle the logic
- Routes handle the URL structure and HTTP method mapping
- Keeping them separate improves code readability, structure, and scalability.