如何在纯Express框架中实现Next.js风格的Catch All Routes全捕获路由功能
Got it! Mimicking Next.js's handy [...params] catch-all routing in Express is totally doable—you just need to leverage Express's routing capabilities and a bit of string manipulation to turn captured path segments into an array. Here's how to implement it for your /api/products/[...categories] example:
Basic Implementation (Quick & Direct)
This approach uses a wildcard route parameter to capture all segments after /api/products/, then splits the result into an array that matches the format you want:
const express = require('express'); const app = express(); app.get('/api/products/:categories*', (req, res) => { // Combine the initial parameter and wildcard suffix (if present) let fullCategoryPath = req.params.categories; if (req.params[0]) { // Slice off the leading slash from the wildcard part fullCategoryPath += req.params[0].slice(1); } // Split into an array of category segments req.params.categories = fullCategoryPath.split('/'); // Example response to verify the result res.json({ message: 'Categories received', categories: req.params.categories }); }); app.listen(3000, () => console.log('Server running on port 3000'));
- Testing
/api/products/platesreturns{"categories": ["plates"]} - Testing
/api/products/plates/cupsreturns{"categories": ["plates", "cups"]}
Clean Alternative: Regular Expression Route
If you prefer a more concise route definition, use a regex to directly capture the full path suffix and split it into an array:
app.get(/^\/api\/products\/(.*)$/, (req, res) => { const categoryString = req.params[0]; // Split into array (handle empty case for routes like /api/products/) req.params.categories = categoryString ? categoryString.split('/') : []; res.json({ categories: req.params.categories }); });
- To disallow empty paths (e.g.,
/api/products/), modify the regex to/^\/api\/products\/(.+)$/(requires at least one segment).
Reusable Middleware (For Multiple Routes)
If you want to use this catch-all pattern across multiple routes, create a reusable middleware to avoid repeating code:
function parseCatchAllParam(paramName) { return (req, res, next) => { let paramValue = req.params[paramName]; if (req.params[0]) { paramValue += req.params[0].slice(1); } req.params[paramName] = paramValue.split('/'); next(); }; } // Use for your products route app.get('/api/products/:categories*', parseCatchAllParam('categories'), (req, res) => { res.json({ categories: req.params.categories }); }); // Reuse for a posts route, for example app.get('/api/posts/:slug*', parseCatchAllParam('slug'), (req, res) => { res.json({ slug: req.params.slug }); });
Key Notes
- Express doesn’t natively support array parameters from catch-all routes like Next.js, but splitting the captured string into an array achieves the exact same behavior.
- You can add validation (e.g., checking for empty arrays) if you want to enforce mandatory segments.
内容的提问来源于stack exchange,提问作者Xkoder FX

