Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// routes/products.js — a dedicated router file const express = require('express'); const router = express.Router(); const products = [ { id: 1, name: 'Laptop', price: 999 }, { id: 2, name: 'Monitor', price: 399 }, ]; // GET /products (with optional ?category= query) router.get('/', (req, res) => { const { category, sort } = req.query; let result = products; if (category) result = result.filter(p => p.category === category); if (sort === 'price') result = result.sort((a, b) => a.price - b.price); res.json(result); }); // GET /products/:id router.get('/:id', (req, res) => { const product = products.find(p => p.id === parseInt(req.params.id)); if (!product) return res.status(404).json({ error: 'Not found' }); res.json(product); }); // GET /products/:id/reviews router.get('/:id/reviews', (req, res) => { res.json({ productId: req.params.id, reviews: [] }); }); module.exports = router; // app.js — mount the router: // const productRouter = require('./routes/products'); // app.use('/products', productRouter); // Now: GET /products, GET /products/1, GET /products/1/reviews
Result
Open