Is there a way to configure json-server, when utilized as a module, to introduce delays in its responses

json-server provides a convenient way to introduce delays in responses through the command line:

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

However, when attempting to achieve the same delayed response using json-server as a module, the following code snippet fails to 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);

Surprisingly, the setTimeout function is completely ignored and doesn't execute as expected.

Answer №1

The order of execution plays a crucial role here. Middlewares must always come before the router for proper functioning. Simply moving your timeout function before

server.use(jsonServer.router("db.json"));
should resolve the issue.

Take a look at my implementation:

const app = jsonServer.create();
const router = jsonServer.router(path.join(__dirname, '../../test/api/dev.json'));
const 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('The JSON Server is successfully running on localhost:3000');
  done();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach to alter a user's message depending on the form's ID that was used for submission?

I currently have two separate screens that each serve a specific purpose, where only one can be open at any given time. First is the login form: <form action="/Account/Login" id="login-form" class="form" method="post"> <butto ...

Is Node.js and Express a suitable server-side package for a WebGL web application?

Currently, I am in the process of creating a webgl application. While using mongoDB for my database and three.js as my webgl library has been helpful during development, I find myself unsure about which server-side technology to incorporate into the appl ...

Can context be passed into a component that is created using ReactDOM.render()?

TL;DR In this given example code: ReactDOM.render(<MyComponent prop1={someVar} />, someDomNode); Can one manually provide React context to the instance of MyComponent? This might seem like an unusual question considering React's usual behavio ...

Choosing an Array of Integers in PostgreSQL: A Guide

My goal is to extract arrays of integers from a table in this format: [1, 2, 3] I attempted the following query: (SELECT array_to_json(array_agg(row_to_json(s))) FROM( SELECT specialty FROM talent_specialty WHERE userid = 840 )s); This is the result r ...

What is the best way to assign user input to my JavaScript variables?

As a newcomer to programming, I am eager to develop an app that utilizes the numerical values inputted by customers as variables for calculations. How can I extract the value from an input using JavaScript? For instance, how can I subtract one input value ...

How can I apply JavaScript to aggregate child node values and assign them to the parent in JSON data format?

I receive a dynamic JSON from the server, which has varying structures. Each data entry consists of a chapter with stages and/or review sets at the root level. If a stage exists, there will be either a review set array or another stage. The review set cont ...

Express.js returning unexpected results when calling MySQL stored procedures

I've encountered a strange issue with a stored procedure called getUsers in MYSQL. When I execute the procedure in phpmyadmin, it returns a table of users with their data perfectly fine. However, when I try to call the same procedure from my Node.js a ...

Leverage the `dispatch` hook within a useEffect function

When it comes to triggering an action upon the React component unmounting, I faced a challenge due to hooks not allowing the use of componentWillUnmount. In order to address this, I turned to the useEffect hook: const dispatch = useDispatch(); useEffect(( ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

Issues with changing background colors using Jquery animate

I am attempting to create a fading background color effect when a button is clicked. Currently, I can change the background color using this code: $("#" + lblqty).css("background","#e9f1ff"); However, when I try to use the animate function as shown below ...

What are the steps to transition from @zeit/next-sass deprecation?

Is there a way to transition and modify the next.config.js file to switch from using @zeit/next-sass to leveraging Next.js's built-in support for Sass? Check out this link for more information: https://www.npmjs.com/package/@zeit/next-sass const withS ...

Eliminate every instance using the global regular expression and the replace method from the String prototype

function filterWords(match, before, after) { return before && after ? ' ' : '' } var regex = /(^|\s)(?:y|x)(\s|$)/g var sentence1 = ('x 1 y 2 x 3 y').replace(regex, filterWords) console.log(sentence1) sentence2 ...

Utilizing command line parameters in Node.js through package.json configuration

The Jest documentation includes the following quote: Jest documentation: Node.js v6.* has Proxy enabled by default; if you are not using Node v6.*, be sure to run Jest with node --harmony_proxies node_modules/.bin/jest. My tests are running via npm tes ...

Tips on saving checklist values as an array within an object using AngularJS

I need help with storing selected checklist items as an array in a separate object. I want to only store the names of the checklist items, but I am struggling to figure out how to achieve this. Below is the HTML code: <div ng-app="editorApp" ng-contro ...

Customize the URL path in Next.JS according to the user's location

My Next JS website is hosted on the domain abc.com. I would like the site to automatically detect a visitor's location, retrieve their country code, and then redirect them to abc.com/country_code. ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

What is the best way to convert items from a foreach loop into a JSON string using the json_encode() function in PHP?

I want to populate a string with all the emails fetched from the database, in order to use JavaScript for checking if the email entered by a user in a form field is already registered. I'm attempting to utilize the json_encode() function. $connec ...

Menu icon in Next.js/React/Tailwind not triggering close action when clicked again, causing responsiveness issue

Hey there, I'm relatively new to working with Next.js and React. Right now, I'm tackling the challenge of creating a responsive navbar that toggles open and closed when clicking on the hamburger icon (and should also close when clicked outside th ...

Wordpress is experiencing a recurring issue with scripts being loaded multiple times

Currently, I am attempting to load some of my scripts from CDNs such as CDNjs and Google. While the scripts are loading correctly, I have noticed a strange issue where each script seems to generate two or even three HTTP requests (for the same script). You ...

acquire data from a JSON array

Attempting to extract the SKU from a URL www.mbsmfg.co/shop/coles-grey/?format=json-pretty in JSON format, and display available values under variants for that specific product to users. For example, when a user visits www.mbsmfg.co/shop/coles-grey/, th ...