Node/Koa2[34]: 开发登录功能
·
Yin灏
目录结构
└─src
├─controller
│ └─user.js
└─routes
└─api
└─user.js
controller 层
src/controller/user.js
//...
const { getUserInfo } = require("../services/user");
const { ErrorModel, SuccessModel } = require("../model/ResModel");
const { loginFailInfo } = require("../model/ErrorInfo");
const doCrypto = reuqire("../utils/cryp");
//...
async function login(ctx, userName, password) {
const userInfo = await getUserInfo(userName, doCrypto(password));
if (!userInfo) {
return new ErrorModel(loginFailInfo);
}
if (ctx.session.userInfo == null) {
ctx.session.userInfo = userInfo;
}
return new SuccessModel();
}
//...
module.exports = {
//...
login,
};
处理登录路由
src/routes/api/user.js
//...
const { login } = require("../../controller/user");
// 登录
router.post("/login", async (ctx, next) => {
const { userName, password } = ctx.request.body;
ctx.body = await login(ctx, userName, password);
});