9

json-server allows one to configure responses to be delayed via the command line:

json-server --port 4000 --delay 1000 db.json

How does one try to do this when using json-server as a module? The following doesn't work:

const jsonServer = require('json-server')
var server = jsonServer.create();

server.use(jsonServer.defaults());
server.use(jsonServer.router("db.json"));
server.use(function(req, res, next) {
    setTimeout(next, 1000);
});

server.listen(4000);

It just ignores the setTimeout function completely and doesn't execute it.

rityzmon
  • 1,945
  • 16
  • 26
  • Perhaps the following is useful to know: https://github.com/typicode/json-server/blob/2b26630ac6379fba77eb104b22e83b41a004b52e/src/cli/run.js#L77 – Marc Scheib Apr 01 '17 at 14:14

1 Answers1

15

The order is important. Middlewares should be before the router. If you move your timeout before server.use(jsonServer.router("db.json")); it should work.

Here is my working example:

var app = jsonServer.create();
var router = jsonServer.router(path.join(__dirname, '../../test/api/dev.json'));
var middlewares = jsonServer.defaults();

app.use(function(req, res, next){
  setTimeout(next, 10000);
});
app.use(middlewares);
app.use(router);

server = app.listen(3000, function () {
  console.log('JSON Server is running on localhost:3000');
  done();
});
Marc Scheib
  • 1,963
  • 1
  • 24
  • 29