Json-server: How to mock a api for login?

Created on 24 Oct 2016  路  6Comments  路  Source: typicode/json-server

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"
}

Most helpful comment

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.

All 6 comments

@littlee it depends on what do you expect when posting to /login:

  • if you expect to add the user in the body, you should use an array instead of object for the login route
{
  "login":[ {
    "username": "my name",
    "role": ["admin"]
  }]
}
  • if you expect to update the current user, you should:

    • Do a PUT instead of POST

    • use id

    • your path should be /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.

Was this page helpful?
0 / 5 - 0 ratings