typicode / json-server

Get a full fake REST API with zero coding in less than 30 seconds (seriously)
Other
72.82k stars 7.02k forks source link

disable db.json file rewriting during POST request #819

Open msafronov opened 6 years ago

msafronov commented 6 years ago

hi! i have a json.db file, which contains response objects for a client. i want to simulate authentication scenario by POST http request, where user sends his credentials to the json-server (for example: login, password) and get a jwt-token pair as a response. but after this request, db.json file is changed and route object has a user credentials instead of token pair.

how can i make json-server immutable? it has read-only flag, but it's just deprecate all query types besides GET, and it's not what i want. thanks!

msninela commented 6 years ago

Hello kotoo,

Not an answer to your question, a question instead. I am failing to get the db.json to work. May you please see if you have an answer to my issue? https://github.com/typicode/json-server/issues/821

mcherb commented 5 years ago

@msafronov did you resolve this issue ? i get the same problem

msninela commented 5 years ago

@mcherb please see if issue #821 can help.

diegoleme commented 4 years ago

You can use a middleware

# mock-api/signIn.js
module.exports = (req, res, next) => {
    delete req.body.idToken
    next()
}
$ json-server --watch mock-api/db.json --middlewares mock-api/signIn.js
typekev commented 4 years ago

For @msafronov, @mcherb, and anyone else who stumbles on this, the solution provided here https://github.com/typicode/json-server/issues/581#issuecomment-463229983 worked for me.

I ended up doing something like this:

// middleware.ts
module.exports = (req, res, next) => {
    if (req.method === 'POST') {
      req.method = 'GET';
    }
    next();
}
$ json-server --watch db.json --middlewares middleware.ts
thlindustries commented 3 years ago

Hey bro, I think that I've found a solution to a 'read-only', I don't know if this was a recent update or not but here we go. Looking at the types of js-server .defaults() I found a guy callend MiddlewaresOptions and on it we have a param called readyOnly which has a description: "Accept only GET requests", so if you use this it might solve your problem:

const middlewares = jsonServer.defaults({readOnly: true});
server.use(middlewares);

The only problem is if you want to do a POST, on readOnly mode i think that the server is just able to handle GET requests