koa
Koa 是一个新的 web 框架,由 Express 幕后的原班人马打造, 致力于成为 web 应用和 API 开发领域中的一个更小、更富有表现力、更健壮的基石。 通过利用 async 函数,Koa 帮你丢弃回调函数,并有力地增强错误处理。 Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法,帮助您快速而愉快地编写服务端应用程序。
//类似于http。包装过的http对象
const koa=require('koa')
//创建http服务器,监听请求
const app=new koa()
//监听当前机器的地址,端口
app.use((ctx,next)=>{
ctx.body='hello koa';
})
app.listen(80)
//热重载 supervisor npm i -g supervisor supervisor app就可以使用了
//客户端发请求到看到内容
context 对象
每一次请求都会包装一个 context 对象
该对象对 node 的 request 和 response 对象进行了封装(加强了node中的request和response)
同时提供了其他一些有用的 api
koa 会把 context 传入到中间件函数的第一个参数中
可以对context进行扩展,并在中间件中使用
- .req:Node 的 request 对象
- .res:Node 的 response 对象
注意:在 Koa 中尽量使用Koa提供的封装对象 - .request:Koa 的 request 对象
- .response:Koa 的 response 对象
- .state:用户数据存储空间
- .app:当前应用程序实例 - Application 对象
context 对象
request 对象
注:在 Koa 中,request 对象是 Context 对象下的一个属性,为了方便调用 request 对象下的一些常用属性与方法同时在 Context 下有对应的挂载,也就是 Context 下的一些属性与方法等同于 request 对象下的对应属性和方法,response也是如此 - .throw([status][, msg][, properties])
抛出一个错误,Koa 会进行处理(比如返回对应的响应信息)
在app.on(‘error’)事件中可以捕获到该异常,error 参数中也会保存msg和properties
request 对象 - .header:头信息对象,别名:headers
- .header=:设置头信息,别名:headrs=
- .method:请求方法
- .method=:设置请求方法
- .length:请求正文内容长度
- .url:请求URL
- .url=:设置请求URL,不包含协议与主机部分
- .orginalURL:原始URL,不包含协议与主机部分
- .res:Node 的 response 对象
- .href:原始完整URL,包含协议、主机、请求串
- .path:URL路径部分
- .path=:设置URL路径
- .querystring:URL中的querystring
- .querystring=:设置URL中的querystring
- .search:URL中的search,带 ? 的querystring
- .search=:设置URL中的search
- .host:请求头中的host
- .hostname:请求头中的hostname
- .URL:解析过的URL对象
- .type:请求头中 content-type
- .charset:请求头中的charset
- .query:解析过的querystring对象
- .query=:设置querystring对象值
- .fresh:判断缓存设置时候有效,true表示有效
- .stale:与fresh相反
- protocol:请求使用的协议
- .secure:是否是安全协议,protocol==‘https’
- .ip:请求客户端 IP
- .ips:请求客户端所有 IP(比如使用了代理等)
- .subdomains:子域名数组
- .is(types…):判断提交内容的MIME类型
//类似于http。包装过的http对象
const koa=require('koa')
//创建http服务器,监听请求
const app=new koa()
//监听当前机器的地址,端口
//use注册中间件函数
app.use((ctx,next)=>{
//ctx经过koa处理过的对象
console.log(1)
let n=Math.random()
ctx.state.n=n
ctx.body='<h1>hello koa</h1>';
// ctx.throw('404','页面没有',{a:1})
console.log(ctx.request)
next()
})
//app.use(async (ctx,next)=>{
app.use((ctx,next)=>{
//ctx经过koa处理过的对象
//async异步
console.log(ctx.state.n)
ctx.body+='hello2 koa';
console.log(4)
//await debugger.findeone()
// ctw.throw() 抛错
next()
})
// app.use((ctx,next)=>{
// throw new Error()
// })
app.on('error',err=>{
console.log('错误 ',err);
})
app.listen(80)
//热重载 supervisor npm i -g supervisor supervisor app就可以使用了
//客户端发请求到看到内容 服务器接收请求-->外理请求,生成数据--发送数据
/**koa request ->middleware ->response
* koa处理了request response 我们需要是注册中间件
* Application
*
*
*
*/
- koa-static-cache:静态文件代理服务
- koa-router:路由
- koa-swig:模板引擎
- koa-bodyparser:body解析
- koa-multer:formData解析
npm i koa-static-cache
//类似于http。包装过的http对象
const koa=require('koa')
const koaStaticCache = require('koa-static-cache')
//创建http服务器,监听请求
const app=new koa()
//监听当前机器的地址,端口
//use注册中间件函数 有请求,通过staticCache进行处理
app.use(koaStaticCache(__dirname+'/static',{
dir:__dirname+'/static',
prefix:'/public' //如果当前请求的url是以public开始,刚作为静态资源
}))
app.use((ctx,next)=>{
})
app.listen(80)
//热重载 supervisor npm i -g supervisor supervisor app就可以使用了
//客户端发请求到看到内容 服务器接收请求-->外理请求,生成数据--发送数据
/**koa request ->middleware ->response
* koa处理了request response 我们需要是注册中间件
* Application
*
*
*
*/
路由
require(‘koa-router’)
npm i koa-router
koa-router:路由
- 嵌套路由
const parent = new Router()
const child = new Router()
parent.use(’/p’, child.routes()) - 路由前缀
const router = new Router({
prefix: ‘/user’
})
//类似于http。包装过的http对象
const koa=require('koa')
const koaStaticCache = require('koa-static-cache')
//创建http服务器,监听请求
const app=new koa()
//监听当前机器的地址,端口
const Router = require('koa-router')
const router = new Router()
//use注册中间件函数 有请求,通过staticCache进行处理
app.use(koaStaticCache(__dirname+'/static',{
dir:__dirname+'/static',
prefix:'/public' //如果当前请求的url是以public开始,刚作为静态资源
}))
// app.use((ctx,next)=>{
// console.log(ctx.URL)
// })
router.get('/',(ctx,next)=>{
ctx.body="hi"
})
//子路由
const itemRouter = new Router({
prefix:'/item'
})
// itemRouter.get('/',(ctx,next)=>{
// ctx.body="首页"
// })
// itemRouter.get('/',(ctx,next)=>{
// ctx.body="地址"
// })
itemRouter.get('/add',(ctx,next)=>{
ctx.body="地址"
})
// router.use('/user',itemRouter.routes())
//把路由对象挂到app对象中
app.use(router.routes())
app.use(itemRouter.routes())
app.listen(80)
//热重载 supervisor npm i -g supervisor supervisor app就可以使用了
//客户端发请求到看到内容 服务器接收请求-->外理请求,生成数据--发送数据
/**koa request ->middleware ->response
* koa处理了request response 我们需要是注册中间件
* Application
*
*
*
*/
koa-router:路由
- 动态路由
router.get(’/user/:id’, cb);
动态路由参数通过 ctx.params 对象获取 - 路由重定向
router.redirect(’/user’, ‘/login’, 301) - URL生成器
Router.url(’/list’, {page:1}, {query{order:‘desc’}}) 生成:/list/1?order=desc
koa-swig:模板引擎
安装使用
npm i koa-swig
const Swig = require(‘koa-swig’)
const render = Swig(options)
加载 co 模块
koa v2.x 需要使用 co 函数
npm i co
const co = require(‘co’)
koa-swig:模板引擎
把渲染方法挂载到 Context 下
app.context.render = co.wrap( render(opts) ) opts:
- root: 模板存放目录
- autoescape:是否自动 escape 编码
- cache:是否启用缓存
- ext:模板后缀,‘html’
koa-swig:模板引擎
render & data
ctx.body = await ctx.render(模板文件, 数据)
koa-swig:模板引擎
模板语法
输出:{{表达式}}
判断
{% if 条件 %}{% endif %}
{% if 条件 %}{%elseif 条件%}{% endif %}
{% if 条件 %} {%else%}{% endif %}
koa-swig:模板引擎
模板语法
循环
{% for x in y %}{% endfor %}
{%for key, val in data%}
内置变量
loop.index:从1计算
loop.index0:从0计算
loop.length:长度
koa-swig:模板引擎
模板语法
继承
{% extends “base.html” %}
{% block name %}{% endblock %}
类似类的方法,子模板可以重写
koa-swig:模板引擎
模板语法
包含导入
{% include ‘widget.html’ %}
变量设置与传参
{% set name = ‘zMouse’ %}
{% include ‘widget.html’ with name %}
在使用 include 的模板中可以使用 name
koa-bodyparser:body解析、数据提交
安装
npm i koa-bodyparser
使用
const bodyParser = require(‘koa-bodyparser’)
app.use( bodyParser([opts]) )
该中间件会在解析来自正文的数据以后,把解析后的数据挂载在ctx.request.body下面
后端渲染模板 todolist
链接:https://pan.baidu.com/s/1j1U31bNCnsa7gTneo9H7Rw
提取码:klxh
复制这段内容后打开百度网盘手机App,操作更方便哦
运行 node app 或者是supervisor app
前端渲染模板
链接:https://pan.baidu.com/s/1VHmJxibcCI4b4h7xO3nOJQ
提取码:52uh
运行 node app 或者是supervisor app
http://127.0.0.1/static/index.html