二、从零模拟新浪微博-基本环境搭建
介绍
将用户的session存放在redis中。
安装依赖
yarn add koa-redis koa-generic-session配置session
配置session需要在注册路由前进行配置。
// ...
// session配置(加密密匙)
app.keys = ['XiaoKang666']
app.use(
session({
// cookie的name 默认是 koa.sid
key: 'weibo.sid',
// redis key 的前缀 默认是 koa.sess
prefix: 'weibo:sess:',
cookie: {
path: '/',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000
},
store: redisStore({
all: `${REDIS_CONF.host}:${REDIS_CONF.port}`
})
})
)
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
使用session时只需要为ctx的session操作即可。
router.get('/json', async (ctx, next) => {
const session = ctx.session
if (session.viewNum == null) {
session.viewNum = 0
}
session.viewNum++
ctx.body = 'session.viewNum:' + session.viewNum
})单元测试
单元测试使用jest,
*.test.js文件- 常用的断言
- 测试http接口
安装插件
yarn add --dev jest修改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": "cross-env NODE_ENV=test jest --runInBand --forceExit --colors"
}测试函数
/**
* @author 小康
* @description test demo
*/
function sum(a, b) {
return a + b
}
test('10+20=30?', function () {
const res = sum(10, 20)
expect(res).toBe(30)
})测试http请求
/**
* @author 小康
* @description json test
*/
const server = require('./server')
test('json接口返回数据格式正确', async () => {
const res = await server.get('/json')
expect(res.body).toEqual({
title: 'koa2 json'
})
})开发环境搭建
eslint
安装插件
yarn add --dev eslint babel-eslint编写配置文件
忽略的文件
node_modules test src/public这些目录下的文件将忽略eslint语法检查
eslint规则
{ "parser": "babel-eslint", "env": { "es6": true, "commonjs": true, "node": true }, "rules": { "indent": ["error", 2], "quotes": [ "error", "single", { "allowTemplateLiterals": true } ], "semi": ["error", "never"] } }
修改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",
"lint": "eslint --ext .js ./src",
"test": "cross-env NODE_ENV=test jest --runInBand --forceExit --colors"
}此时运行yarn lint即可检查。
为了规范每次提交前运行命令进行代码检查,因此还需要插件pre-commit
yarn add --dev pre-commit修改package.json脚本
{
"pre-commit":["lint"]
}debug
修改运行脚本
"scripts": {
"dev": "cross-env NODE_ENV=dev ./node_modules/.bin/nodemon --inspect=9229 bin/www",
},通过访问chrome://inspect/即可看到。
404、错误页面
路由配置
/**
* @author 小康
* @description error 404路由
*/
const router = require('koa-router')()
// 错误页面
router.get('/error', async function () {
await ctx.render('error')
})
// 兜底 404
router.get('*', async function (ctx) {
await ctx.render('404')
})
module.exports = router注册路由时应该将这个路由放到最后。
const index = require('./routes/index')
const users = require('./routes/users')
const errorViewRouter = require('./routes/view/error')
// ....
const { isProd } = require('./utils/env')
// 处理错误页面
let onErrorConfig = {}
if (isProd) {
onErrorConfig.redirect = '/error'
}
onerror(app, onErrorConfig)
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods()) 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小康博客!
评论
TwikooDisqusjs










