koa基础
安装
npm install -g koa-generator
初始化
// -e 基于es
koa2 -e koa2-learn
// node js
koa2 project
global.console.log(123)
app.js
const Koa = require('koa')
const app = new Koa()
// 自定义中间件
const qv = require('./new_qv/qv.js')
// 使用中间件 app.use(回调函数)
app.use(qv)
// 创建中间件 环状请求 进去执行一次(进去快) 出来执行一次(出来慢)
// next: 执行下个中间件 // 都需要执行next 不然就中止
router 请求
获取参数
- get请求: ctx.params[x] ctx.query[x]
- post请求: ctx.request.body[x]
app.js引用
const index = require('./routes/index')
const users = require('./routes/users')
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
router/index.js
// 创建
const router = require('koa-router')()
router.get('/', async (ctx, next) => {
// global.console.log(1)
await ctx.render('index', {
title: 'Hello Koa 2!'
})
})
router.get('/error', async (ctx, next) => {
await ctx.render('error', {
message: '错误信息',
error: {
status: 500,
stack: '服务器错误'
}
})
})
router.get('/string', async (ctx, next) => {
ctx.body = 'koa2 string'
})
router.get('/json', async (ctx, next) => {
ctx.body = {
title: 'koa2 json'
}
})
module.exports = router
user.js
const router = require('koa-router')()
// 补充前缀
router.prefix('/users')
router.get('/', function (ctx, next) {
ctx.body = 'this is a users response!'
})
// responds to user/bar
router.get('/bar', function (ctx, next) {
ctx.body = 'this is a users/bar response'
})
module.exports = router
嵌套路由 Nested routers 支持多个中间件 获取传参params
var forums = new Router();
var posts = new Router();
posts.get('/', (ctx, next) => {...});
posts.get('/:pid', (ctx, next) => {
console.log(ctx.params)
// 传参params => {pid: ''}
},(ctx, next) => {
// do 多个操作
});
forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods());
// responds to "/forums/123/posts" and "/forums/123/posts/123"
app.use(forums.routes());
cookies
ctx.cookies.get(name, [options])
通过 options 获取 cookie name:
- signed 所请求的cookie应该被签名
koa 使用 cookies 模块,其中只需传递参数。
ctx.cookies.set(name, value, [options])
通过 options 设置 cookie name 的 value :
- maxAge 一个数字表示从 Date.now() 得到的毫秒数
- signed cookie 签名值
- expires cookie 过期的 Date => date对象
- path cookie 路径, 默认是’/’
- domain cookie 域名
- secure 安全 cookie
- httpOnly 服务器可访问 cookie, 默认是 true
- overwrite 一个布尔值,表示是否覆盖以前设置的同名的 cookie (默认是 false). 如果是 true, 在同一个请求中设置相同名称的所有 Cookie(不管路径或域)是否在设置此Cookie 时从 Set-Cookie 标头中过滤掉。
koa 使用传递简单参数的 cookies 模块。
koa-generic-session kod-redis
npm i koa-generic-session kod-redis
启动redis
redis-server
app.js
// redis seesion
const Redis = require('koa-redis')
const session = require('koa-generic-session')
// session加密处理的两字符
app.keys = ['keys','key']
// 连接
app.use(session({
// key, prefix 前缀
key: 'egg',
prefix: 'e',
store: new Redis()
}))
读写 => ctx
const login = async (ctx) => {
// 直接存写session
ctx.session.count++
// console.log(ctx.session.count)
const uid = ctx.cookies.get('uid')
if (uid) {
// console.log(uid);
} else {
ctx.cookies.set('uid', parseFloat(Math.random().toFixed(10) * Math.pow(10, 10)), {
expires: new Date(Date.now() + min(1))
})
}
}