I was wondering how to use json-server to mock my login API
db.json
{
"login": {
"username": "my name",
"role": ["admin"]
}
}
when I POST to /login with body below, it delete the resource under login route
{
"username": "user_name",
"password": "123456"
}
@littlee it depends on what do you expect when posting to /login:
{
"login":[ {
"username": "my name",
"role": ["admin"]
}]
}
PUT instead of POSTid/login/{userid}currently, what you described is very normal and expected behavior for POST
@Nilegfx I would like to return a fixed JSON for the server when a user logs in
Did anyone figure this out?
I found that we could use middleware.
// login-middleware.js
module.exports = (req, res, next) => {
if (req.method == 'POST' && req.path == '/login') {
if (req.body.username === 'a' && req.body.password === 'a') {
res.status(200).json({})
} else {
res.status(400).json({message: 'wrong password'})
}
} else {
next()
}
}
Then launch app with --middleware option:
$ ./node_modules/.bin/json-server --watch mock-api/db.json --port 3001 --middlewares mock-api/login-middleware.js
In this way we could mix some custom logic into json-server built-in APIs.
@soasme I did try the middleware suggested by you. Though the request does not seem to pass through this middleware nor the middleware is being executed. Any Idea what could be wrong. Can you provide a working example which I can refer to? TIA
@vikashpisces I'd like to help you but you didn't provide any gist or code snippet of how you made your experiment.
Most helpful comment
I found that we could use middleware.
Then launch app with
--middlewareoption:In this way we could mix some custom logic into json-server built-in APIs.