json-server模拟实现登录接口

670 阅读1分钟

json-server通过nodejs实现模拟登录接口

middleware.js

module.exports = (req, res, next) => {
  if(req.method === 'POST'&& req.path === '/login') {
    if(req.body.username === 'hj' && req.body.password === '123') {
      return res.status(200).json({
        user:{
          token:'123'
        }
      })
    }else{
      return res.status(400).json({message:'用户名或者密码错误'})
    }
  }
  next()
}

此中间件文件需要用commonjs规范写,运行json-server时启动

package.json

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "json-server": "json-server __json_server__/db.json --watch --port 3001 --middlewares ./__json_server__/middleware.js"
  },