What I’m going to say is a bad idea.
Sometimes it may be necessary to force the hand a little for not quite standard requests. This is the case when a BE, when faced with a request with the POST
/PUT
/DELETE
method, returns an answer that would be more appropriate for a GET
call.
The json-server
certainly helps us to mock requests like this but among its features there is also that of going to modify the db.json
every whenever we send him a POST
request for a dummy object.
To prevent this from happening and indeed return an arbitrary output there is a need for forcing, inserting a configuration that allows us to return regardless of the data.
We can do this by adding a configuration to the launch of our mock server, the middlewares
parameter:
json-server --middlewares mocks/server.js --port=4201
Pointing it to a configuration file that intercepts all calls and manages those in another way, for example, with the POST
method:
// mocks/server.js
// Replace POST method with GET to avoid 201 on POST.
module.exports = (req, res, next) => {
if (req.method === 'POST') {
// Is a POST request. Change its method to return something from db.json.
req.method = 'GET';
next();
} else {
// Not a post request. Let db.json handle it
next();
}
};
I hope you find this little widget useful.
Don’t try it at home!