You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过中间件为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.json endpoints)
  • Optional: Clear the default root routes so users can’t access /posts directly anymore—only /api/v2/posts works
  • Reattach that router to the /api/v2 prefix, 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 /posts will 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:58:22