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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With