无论如何,JSON服务器都可以声明Anon-CLI中间件



使用JSON服务器,我们可以声明Cli Middlewares

You can add your middlewares from the CLI using --middlewares option:
// hello.js
module.exports = (req, res, next) => {
  res.header('X-Hello', 'World')
   next()
}
json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js

但是如何在我的node.js代码中声明使用json-server中间件?

我试图将其推入中间件阵列

 const jsonServer = require('json-server')
 const apiServer = jsonServer.create()  // Returns an Express server for the API
 const apiMiddlewares = jsonServer.defaults() // Returns middlewares used by JSON Server.
 apiMiddlewares.push((req, res, next)  => {
   console.log(new Date(), req.method, req.url)
   next()
 })
 console.log('API MIDDLEWARES ARRAY: ', apiMiddlewares)

它已添加到数组中,但从未使用过...没有显示

通过将我的中间件移至前线来解决...

app.use('/api',function(req, res, next){
   console.log('A new request received at ' + Date.now())
   next()
})

最新更新