koa
什么是koa?
- 基于Node.js的下一代web应用开发框架
- express 进阶版
- domain 环境
koa基础
const Koa=require('koa')
const app=new Koa()
// ctx(context)即req,res,next的结合体
app.use(async ctx=>{
// ctx.res
// ctx.req
ctx.body='hello world'
})
app.listen(3000,'localhost',()=>{
console.log(`the server is running on http://localhost:3000`)
})
koa级联
- 当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开并且每个中间件恢复执行其上游行为。
- ctx.set() //设置请求头 headers
app实例
- app.porxy代理 ->解决跨域问题
- app.env -> 环境问题 (决定代码要不要被压缩)
- 开发环境: 代码开发阶段所处的环境
- 生产环境:开发阶段的代码经过编译、压缩后文件运行的环境
- 测试环境:开发阶段的代码经过编译、压缩后文件,进行代码质量检测、语法检测
- 上线环境: 开发阶段的代码经过编译、压缩后文件,放在云服务器或是主机中运行
- app.listen(…) 方法只是以下方法的语法糖:
- http.createServer(app.callback()).listen(3000);
- 可以同时开多个服务器端口,显示相同内容
- app.listen(3000)
- app.listen(3001) port:1-60000
context(ctx)上下文
- app.context
- app.context 是从其创建 ctx 的原型。您可以通过编辑 app.context 为 ctx 添加其他属性。
- 事件的订阅和发布
- ctx.app.on(’’,()=>{})
- ctx.app.emit(’’)
- ctx.cookie
- 设置cookie:
- ctx.cookie.set(key,value,[options])
value不能存放中文,要用querystring(escape/unescape)模块进行编码转换 - 获取cookie:
- ctx.cookie.get(‘name’);
- options的值及含义
- maxAge:多少毫秒以后过期
- expires:到某个时间过期
- path:cookie路径,默认为’/’
- domain:cookie域名
- secure:安全cookie,默认为false,设置为true表示只有https可以访问
- httpOnly:是否只是服务器可以访问cookie,默认为true
router.get('/', async (ctx, next) => {
ctx.cookies.set("userInfo","gouzi",{
maxAge:1000*60*60
})
await ctx.render('index', {
title: 'Hello Koa 啊啊啊啊!'
})
})
let userInfo = ctx.cookies.get("userInfo");
koa路由
- 安装koa-route模块 npm install koa-route -S
const router = require('koa-route')
// 使用路由中间件
app.use(router.get('/about',aboutRouter))
// 路由配置
const aboutRouter=ctx=>{
ctx.body='about页面'
}
nodejs中文编码转换
中文编码: qs.escape(‘中文’)
中文译码: qs.unescape(‘中文编码’)