Egg.js实战:重构用户登录接口

Egg.js实战:重构用户登录接口

引言

在本篇博客中,我们将使用Egg.js框架来重构用户登录接口。我们将从添加路由开始,然后配置token,接着在service中处理密码,生成token,最后添加controller。我们还将使用Postman进行接口验证。

添加路由

首先,我们需要在router.js中添加路由。这里我们使用router.post方法,将/users/login路径映射到controller.user.login方法。

js 复制代码
module.exports = app => {
  const { router, controller } = app;
  router.post('/users/login', controller.user.login)
};

配置token

接着,我们需要在config.default.js中添加token配置。这里我们使用jsonwebtoken库,设置了secret和expiresIn。

js 复制代码
module.exports = appInfo => {
  // ...其它代码
  config.jwt = {
    secret: 'f2d1c153-39ec-4327-8c86-0d7308ad84f0',
    expiresIn: '1d'
  }

  return {
    ...config,
    ...userConfig,
  };
};

处理密码

在service中,我们需要处理密码。因为在model中,我们设置了password为不可选,但是在登录时,我们需要通过email查找到password进行比对,所以我们需要在service中进行处理。

js 复制代码
const Service = require('egg').Service
const jwt = require('jsonwebtoken')

class UserService extends Service {
  // ...其它代码
  findEmail(email) {
    return this.User.findOne({
      email
    }).select('+password')
  }
}

module.exports = UserService

生成token

在service/user.js中,我们需要封装token相关的方法。这里我们使用jsonwebtoken库来生成token。

添加controller

最后,我们需要在controller/user.js中添加controller。这里我们首先验证了用户输入的email和password,然后查找用户,如果用户不存在或者密码不正确,我们将抛出错误。如果验证通过,我们将生成token,并返回用户信息和token。

js 复制代码
const Controller = require('egg').Controller
class UserController extends Controller {
  async login() {
    const userBody = this.ctx.request.body
    this.ctx.validate({
      email: { type: 'string' },
      password: { type: 'string' }
    }, userBody)

    const user = await this.service.user.findEmail(userBody.email)
    if (!user) {
      this.ctx.throw(422, '用户未注册')
    }
    if (this.ctx.helper.md5(userBody.password) !== user.password) {
      this.ctx.throw(422, '密码不正确')
    }

    const token = this.service.user.createToken({ user })
    let userinfo = user._doc
    delete userinfo.password
    this.ctx.body = {
      ...userinfo,
      token
    }
  }
}

module.exports = UserController

Postman验证

最后,我们使用Postman进行接口验证,验证结果如下图所示:

总结

以上就是使用Egg.js重构用户登录接口的全部内容。通过这个过程,我们可以看到Egg.js在处理用户登录这样的常见需求时,其强大的功能和灵活性。

相关推荐
Cosolar9 小时前
不收费、不加水印、数据归你:我做了个开源的在线简历工具
后端·面试·前端框架
小蒜学长10 小时前
基于Spring Boot+Vue3的在线医疗咨询系统的设计与实现(代码+数据库+LW)
java·spring boot·后端·在线问诊·在线医疗咨询系统
陈随易10 小时前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
每天一道题11 小时前
CAP、Raft 与多数派:分布式系统如何达成一致?
分布式·后端·微服务
Moshow郑锴11 小时前
Ansible 批量部署 Node.js 服务:ZIP 直解与共享目录分发两种方案对比
node.js·ansible
前端的日常11 小时前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
IT_陈寒12 小时前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端
ServBay12 小时前
本地模型已经跑起来了,Copilot Fusion 为什么还要联网?
后端·ai编程·github copilot
武子康13 小时前
H3-World 的动作没按时发生,先检查时间线变成了什么
人工智能·后端·agent
苍何13 小时前
腾讯 Buddy One 来了,办公全家桶一键打通WorkBuddy(附教程)
后端