json-server icon indicating copy to clipboard operation
json-server copied to clipboard

json-server does not use the code provided in the middleware file

Open natalie-o-perret opened this issue 7 years ago • 4 comments

I am using json-server to simulate some api calls responses for front-end development turns out that adding a middleware does not really work out in my case:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "concurrently -k \"json-server --watch api-faked/db.json --routes api-faked/routes.json --middlewares api-faked/middleware.js --ro\" \"vue-cli-service serve\"",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },

When starting:

[1]  INFO  Starting development server...
[0]
[0]   \{^_^}/ hi!
[0]
[0]   Loading api-faked/db.json
[0]   Loading api-faked/routes.json
[0]   Loading api-faked/middleware.js
[0]   Done
[0]

It seems that the middleware.js is considered by json-server, however, a simple example such as the middleware.js like below:

module.exports = (req, res, next) => {
    res.header('X-Hello', 'World')
    next()
}

Does not add any header to my response headers:

Request URL: http://localhost:3000/api/v1/operations/?code_like=adi
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: 127.0.0.1:3000
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: authorization
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: http://localhost:8080
Connection: keep-alive
Content-Length: 0
Date: Thu, 18 Jul 2019 12:23:53 GMT
Vary: Origin, Access-Control-Request-Headers
X-Powered-By: Express

What am I missing here?

Side-note: actually removing the next from the middleware.js does not even alter anything, it's like even though the middlware has been added to the json-server configuration it seems not really run at any point in time.

natalie-o-perret avatar Jul 18 '19 12:07 natalie-o-perret

Have you tried using it as a module instead of through the cli?

// server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

server.use(middlewares)

// Add custom middleware before JSON Server router
server.use((req, res, next) => {
  console.log('Time:', Date.now())
  next()
})

server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
})

Docs section: https://github.com/typicode/json-server#module

I've had success using this method, however I've noticed that I don't seem to be able to add middleware after server.use(routes), or add custom middleware to the router at all.

samuelcolburn avatar Jul 20 '19 17:07 samuelcolburn

Thanks for your answer!

Managed to make it work with the module which includes custom routes too:

const fs = require('fs');
const jsonServer = require('json-server');
const path = require('path');
const server = jsonServer.create();
const middlewares = jsonServer.defaults();

server.use(middlewares);
server.use(jsonServer.bodyParser);

// Define custom routes (routes.json)
const routes = JSON.parse(fs.readFileSync(path.join(__dirname, 'routes.json')));
server.use(jsonServer.rewriter(routes));

// Add custom middleware before JSON Server router
server.use((req, res, next) => {
    next()
});

const router = jsonServer.router(path.join(__dirname, 'db.json'));
server.use(router);
server.listen(3000, () => {
    console.log('JSON Server is running')
});

I've had success using this method, however I've noticed that I don't seem to be able to add middleware after server.use(routes), or add custom middleware to the router at all.

Yea this is weird though, not sure this is the expected behaviour of json-server...

natalie-o-perret avatar Jul 22 '19 08:07 natalie-o-perret

My configuration:

const jsonServer = require('json-server')
const data = require('./db.js')
const routes = require('./routes.json')

const router = jsonServer.router(data) // Express router
const server = jsonServer.create()       // Express server
const middlewares = jsonServer.defaults()

server.use(middlewares)
server.use(jsonServer.rewriter(routes))
server.use(router)

// Avoid CORS issue
server.use( (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

server.listen(9538, () => { // 监听的端口
  console.log('JSON Server is running')
})

PLQin avatar Sep 09 '20 02:09 PLQin

Unfortunately this is still an issue on v 0.16.3. The documentation says you can load middleware through the cli with the --middlewares flag, but it does not add your provided middleware to the server. I would like to use the CLI instead of the module so the solution here is more of a work around for those who can use the module.

tsjohns9 avatar Dec 03 '20 17:12 tsjohns9