上節回顧
-
@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結果 register結果](http://static.javashuo.com/static/loading.gif)
![斷點數據 斷點數據](http://static.javashuo.com/static/loading.gif)
註冊邏輯
更新註冊邏輯
// 更新文件:/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結果 register結果](http://static.javashuo.com/static/loading.gif)
- 存儲結果直接返回,會將
password
返回,這裏自行過濾掉敏感信息。
數據庫結果
![robot robot](http://static.javashuo.com/static/loading.gif)
登陸邏輯
更新註冊邏輯
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測試 login測試](http://static.javashuo.com/static/loading.gif)
常見問題
- 查看服務端是否啓動
- 查看請求方式
Method
是否正確
- 多用斷點調試問題
課後嘗試
-
/server/app.js
中app.use(bodyParser())
註釋掉,看看是否還能ctx.request.body
是否存在
- 用斷點多看一下
ctx
的結構
參考文檔
koa-body
mongoosejs#Model Apihtml