Node.js API Layering Example
Routes handle only forwarding; business logic resides in the service layer to facilitate unit testing.
Node.jsjavascript
javascript
1import { Router } from express;2import { List Articles } from "../services/article.js";34const router = Router();56router.get(/articles, async (request, result, next) => {7 try {8 const data = wait List Articles({ page: request.query.page });9 result.json({ code: 0, data });10 } catch (error) {11 next(error);12 }13});1415export default router;Key Points
- Async errors must be passed explicitly to `next`; otherwise, the middleware won't detect them.
- Keep the routing layer free of query statements to facilitate future data source replacements.
Usage suggestions
Run the copied code in a local sample project first to verify expected behavior, then adapt the naming and structure to your business needs. Pasting directly into a large project can cause you to overlook contextual differences.