使用node.js/Express/json-server
我正在尝试检查(并修改)发送到我的 API json 服务器的请求 URL。我在我的应用程序 server.js 中编写了以下中间件
// API JSON-SERVER
const jsonServer = require('json-server')
const apiServer = jsonServer.create()
const apiMiddlewares = jsonServer.defaults()
apiServer.use(apiMiddlewares)
...
apiServer.use((req, res, next) => {
console.log('REQUEST: ', req)
next() // Continue to JSON Server Router
})
...
apiRouter = jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json'))
app.use('/api', apiRouter)
但我从未收到显示的请求 我哪里错了?
最佳答案
我看了这里
https://github.com/typicode/json-server/issues/253
在我看来,你永远不想实例化 jsonServer,而只想使用路由器。由于您使用的是 Express 服务器,因此您应该将中间件附加到该服务器上。
const express = require('express')
const jsonServer = require('json-server')
const app = express()
app.use((req, res, next) => {
console.log('REQUEST: ', req)
next() // Continue to JSON Server Router
})
app.use('/api', jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json')))
关于node.js - json-server 中间件未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47659177/