0

using node.js/Express/json-server

I am trying to check ( and modify) the request url sent to my API json-server. I wrote as stated the following middleware in my app 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)

but I never get the request displayed where am I wrong ?

  • where is app declared? shouldn't be apiServer.use('/api', apiRouter) – Robert Moskal Dec 05 '17 at 17:41
  • I am using ( dev) the same web server ( Express) and db server ( at /api), app is defined above this block .. var app = express() –  Dec 05 '17 at 18:24

1 Answers1

4

I looked here

https://github.com/typicode/json-server/issues/253

and it seems to me that you never want to instantiate the jsonServer, but only use the router. Since you are using the express server, you should attach the middleware to that.

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')))
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
  • that's what I wrote... my concern is related to the middleware... apiServer.use((req, res, next) => {}) Do you mean I better use app.use((req, res, next) => {}) ? –  Dec 06 '17 at 07:53
  • you right ... I can also filter only the requests to the API : pp.use('/api', (req, res, next) => {}) –  Dec 06 '17 at 13:10