Koa & Mongoose & Vue實現先後端分離--05服務端註冊&登陸:業務邏輯

上節回顧

  • @koa/router的用法
  • 用戶路由的定義
  • koa中間件的使用
  • Postman基本測試

工做內容

  • 後端:參數的獲取
  • 後端:數據庫的寫入與查詢
  • Postman:接口測試

準備工做

  • npm i -S koa-body //對Post、Put、Patch請求參數處理

業務邏輯

參數獲取

支持荷載存儲到ctx.request.body

// 更新文件:/server/app.js
const koa = require('koa');
const bodyParser = require('koa-body'); // 新增
const routes = require('./router');

const app = new koa();

app.use(bodyParser());// 新增:在處理請求數據的中間件前調用
//app.use((ctx, next) => {
//  ctx.body = '測試測試測試';
//  next();
//}) //無用代碼刪除
app.use(...router.routes).use(...router.allowedMethods);
routes.forEach(route => {
  app.use(route);
});

app.on('error', err => {
  log.error('server error', err)
});
module.exports = app;

更新註冊&登陸路由

  • 調用POST方法分別訪問/users?action='register'/users?action='login'
  • 經過ctx.query能夠獲取Url上的參數。
// 更新文件:/server/router/users.js部分代碼
...
  {
    path: '/',
    method: 'POST',
    handle: async (ctx) => {
      const { action } = ctx.query;
      switch (action) {
        case 'register':
          await register(ctx);
          break;
        case 'login':
          await login(ctx);
          break;
        default:
          await list(ctx);
      }
    }
  },
...
  • 測試結果

register結果

  • 能夠經過斷點查看數據

斷點數據

註冊邏輯

更新註冊邏輯

// 更新文件:/server/control/user.js
const userModel = require('../model/user');
...
async function register (ctx) {
  const { account, password } = ctx.request.body;//獲取荷載
  if (!account || !password) {
    ctx.body = { // 返回json
      code: '403',
      data: null,
      msg: '賬號/密碼不能爲空'
    }
    return;
  }
  try {
    const user = await userModel.findOne({ // 查看數據庫是否已有數據
      account
    });
    if (user) {
      ctx.body = {
        code: '403',
        data: null,
        msg: '用戶已經存在'
      }
    } else {
      const newUser = await new userModel({ // 新建數據
        account,
        password
      }).save();
      ctx.body = {
        code: '200',
        data: newUser,
        msg: '註冊成功'
      }
    }
  } catch (err) {
    ctx.body = {
      code: '403',
      data: null,
      msg: err.message
    }
  }
}
...
  • 經過ctx.request.body獲取調用POST方法傳過來的參數
  • 經過userModel.findOne(<condition>)查找匹配條件的數據
  • 經過new userModel(<Data>).save()存儲數據

測試邏輯

  • Body面板 --> raw --> JSON格式 --> 輸入參數 --> 查看結果

register結果

  • 存儲結果直接返回,會將password返回,這裏自行過濾掉敏感信息。

數據庫結果

robot

登陸邏輯

更新註冊邏輯

async function login (ctx) {
  const { account, password } = ctx.request.body;
  if(!account || !password) {
    ctx.body = {
      code: '404',
      data: null,
      msg: '參數不合法'
    };
    return;
  }
  const user = await userModel.findOne({
    account,
    password
  });
  if(user) {
    ctx.body = {
      code: '200',
      data: user,
      msg: '登錄成功'
    }
  } else {
    ctx.body = {
      code: '404',
      data: null,
      msg: '賬號/密碼錯誤'
    }
  }
}

測試邏輯

  • Body面板 --> raw --> JSON格式 --> 輸入參數 --> 查看結果

login測試

常見問題

  • 查看服務端是否啓動
  • 查看請求方式Method是否正確
  • 多用斷點調試問題

課後嘗試

  • /server/app.jsapp.use(bodyParser())註釋掉,看看是否還能ctx.request.body是否存在
  • 用斷點多看一下ctx的結構

參考文檔

koa-body
mongoosejs#Model Apihtml

相關文章
相關標籤/搜索