使用json-server模拟登录接口


创建中间件文件 middleware.js

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

  next();
};

登陆逻辑

    
   const login = (param: {username: string, password: string}) => {
        fetch(`${api}/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(param)
        }).then(async (response) => {
            if (response.ok) {
            }
          });
    };

    const handelSubmit = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        const username = (event.currentTarget.elements[0] as HTMLInputElement).value;
        const password = (event.currentTarget.elements[1] as HTMLInputElement).value;
        login({username, password});
    };

配置package.json

  // 这里规定了中间件的入口、json-server的启动、占用端口等
"scripts": {
    "json-server": "json-server __json_server_mock___/db.json --watch --port 4001 --middlewares ./__json_server_mock___/middleware.js"
  },
最后 ,

输入 jack 123456,

就发现登陆成功 返回 一个user 对象,其中为token的字符串。

这样就模拟了接口的登陆。

文章作者: KarlFranz
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 reprint policy. If reproduced, please indicate source KarlFranz !
评论
  目录