1. 改用 koa2 的框架
- express 中间件是异步回调
- koa2 原生支持 async / await
- 新开发框架和系统都基于 koa2 例如 egg.js
async await 要点
- await 后面可以追加 promise 对象, 获取 resolve的值
- await 必须包裹在 async 函数里面
- async 函数执行返回的也是一个 promise 对象
- try-catch 截取 promise 中的 reject 的值
2. koa2 使用
npm install koa-generator -g
Koa2 koa2-test
npm install & npm run dev
npm install cross-env --save-dev
1. package.json 文件里
"scripts": {
"start": "node bin/www",
"dev": "cross-env NODE_ENV=dev ./node_modules/.bin/nodemon bin/www",
"prd": "cross-env NODE_ENV=production pm2 start bin/www",
"test": "echo \"Error: no test specified\" && exit 1"
}
2. 路由配置
- 创建 user.js 在 routes 文件夹里
const router = require('koa-router')()
router.prefix('/api/user')
router.post('/login', async function(ctx, next){
// ctx 包含了 request / response
const { username, password } = ctx.request.body
// 返回数据
ctx.body = {
errno: 0,
username,
password
}
})
module.exports = router
- 在 app.js 里注册路由
const user = require('./routes/user')
app.use(user.routes(), user.allowedMethods())
3. session 实现
npm i koa-generic-session koa-redis redis --save
- app.js 中设置session
const session = require('koa-generic-session')
const redisStore = require('koa-redis')
// 注册路由之前写 session
app.keys = ['abc123']
app.use(session({
// 配置 cookie
cookie: {
path: '/',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000
},
// 配置 redis -> 确认redis开启
store: redisStore({
all: '127.0.0.1: 6379' // 写死本地的 redis
})
}))
4. 开发路由
- 安装 sql xss 插件
npm i mysql xss --save
= sql 获取数据
// 添加 async await
const getList = async (author, keyword) => {
let sql = `select * from blogs where 1=1 `
if(author){
sql += `and author='${author}' `
}
if(keyword){
sql += `and title like '%${keyword}%' `
}
sql += `order by createtime desc;`
return await exec(sql);
}
- routes 里面的改变
// 添加 async await
// req,res -> ctx
router.get('/list', async function (req, res, next) {
let author = ctx.query.author || ''
const keyword = ctx.query.keyword || ''
if(ctx.query.isadmin){
console.log('is admin')
if(ctx.session.username == null){
ctx.body = new ErrorModel("未登录")
return
}
author = ctx.session.username
}
const listData = await getList(author, keyword)
ctx.body = new SuccessModel(listData)
});