如何通过中间件为JSON Server默认实例添加/api/v2请求前缀?
Absolutely! You don’t need to mess with spinning up a custom server instance to add that /api/v2 prefix—middleware is exactly the right tool for extending json-server’s default setup. Here’s a clean, straightforward way to do it:
Step 1: Create a Custom Middleware File
Make a new file (let’s call it add-api-prefix.js) in your project root with this code:
module.exports = (server) => { // Grab the existing router that json-server uses for your endpoints const originalRouter = server._router; // Clear the default routes so only the prefixed ones work (optional) server._router = null; // Mount the original router under the /api/v2 prefix server.use('/api/v2', originalRouter); };
What this does:
- We access json-server’s internal router (the one that handles your
db.jsonendpoints) - Optional: Clear the default root routes so users can’t access
/postsdirectly anymore—only/api/v2/postsworks - Reattach that router to the
/api/v2prefix, so all your existing endpoints are now prefixed
Step 2: Run json-server with the Middleware
Start your server like you normally would, but add the --middlewares flag pointing to your new file:
json-server --watch db.json --middlewares ./add-api-prefix.js
Step 3: Test It Out
- Try hitting
GET /api/v2/posts(or whatever your endpoints are) — it should return your data just like before - If you opted to clear the default routes,
GET /postswill now return a 404 (great for enforcing your API versioning)
Bonus: Keep Both Prefixed and Unprefixed Routes
If you want to support both the original paths and the prefixed ones, just remove the server._router = null; line. That way, /posts and /api/v2/posts both work.
This approach lets you extend json-server’s default instance without having to rewrite your entire server setup—perfect for what you’re looking for!
内容的提问来源于stack exchange,提问作者Robert Strauch

