0

I'm using the JSON Server package (json-server) from https://github.com/typicode/json-server. I'd like to make the server prefix all requests with /api/v2. The documentation even gives an example how to do this with the following:

server.use('/api', router)

However I don't want to setup my own server instance but extend the default when running json-server.

Can I somehow use the above statement in a middleware?

4

1 回答 1

3

由于json-server返回给您的路由器Express 路由器

首先在它自己的路由文件中定义你所有的/v1,/v2等,如下所示:

// api-routes.js
const express = require('express')
const jsonServer = require('json-server')

const router = express.Router()
const server = jsonServer.create()
const middlewares = jsonServer.defaults()
const v1Router = jsonServer.router('db-v1.json')
const v2Router = jsonServer.router('db-v2.json')


router.use('/v1', v1Router)
router.use('/v2', v2Router)

module.exports = router

然后像这样安装你的 API 路由器/api

const express = require('express')
const apiRoutes = require('./api-routes')

const app = express()
app.use('/api', apiRoutes)

// ...

现在应该有/api/v1/api/v2。上面未经测试的代码,但应该知道你需要做什么。

于 2018-03-29T17:51:50.570 回答