标题一、koa与express
1.他们都是node-web开发的框架
2.koa分两个版本,一个是1.x的使用Generator来写,2.x是使用async来写
标题二、说明
1.koa官网介绍,node版本要>7.6才能使用async
2.如果node版本<=7.6,使用async就要配置插件,插件推荐babel-register
3.如果node版本<=7.6,解析和编译async方法至少要有babel-plugin-transform-async-to-generator或者babel-plugin-transform-async-to-module-method
并且需要在.babelrc文件中添加
{
"plugins": ["transform-async-to-generator"]
}
标题三、最基本的用法
1.HTTP服务
koa的特点是优雅、简洁、表达力强、自由度高
koa搭建HTTP服务只需要几行代码
const Koa = require('koa')
const app = new Koa()
app.listen(3000)
然后可以在package.json文件中增加scripts命令
"scripts": {
"build": "node ./src/index.js"
}
接着运行脚本npm run build可以运行这个http服务。但是本地访问http://127.0.0.1:3000,页面显示“not found”。这是因为并没有告诉koa应该显示什么内容。
2、context对象
koa提供一个context对象,表示一次对话的上下文(包括http请求和http回复)。举个栗子
const Koa = require('koa')
const app = new Koa()
const index = ctx => {
ctx.response.body = 'Hello World'
};
app.use(index)
app.listen(3000)
ctx.response代表http的response;那么request代表http的request。
运行上面代码,现在可以看到hello world了。
3、请求(Request)
常用的request的API
API | 说明 | 别名 |
---|---|---|
request.header | 请求标头对象 | request.headers |
request.method | 请求方法。 | |
request.length | 返回以数字返回请求的 Content-Length,或 undefined。 | |
request.method | 请求方法。 | |
request.url | 获取请求 URL. | |
request.originalUrl | 获取请求原始URL。 | |
request.origin | 获取URL的来源,包括 protocol 和 host。 | |
request.href | 获取完整的请求URL,包括 protocol,host 和 url。 | |
request.path | 获取请求路径名。 | |
request.type | 获取请求 Content-Type 不含参数 “charset” | |
request.query | 获取解析的查询字符串, 当没有查询字符串时,返回一个空对象。请注意,此 getter 不 支持嵌套解析。 |
4、响应(Response)
API | 说明 | 别名 |
---|---|---|
response.header | 响应标头对象。 | response.headers |
response.method | 响应方法。 | |
response.status | 获取响应状态。默认情况下,response.status 设置为 404 而不是像 node 的 res.statusCode 那样默认为 200。 | |
response.message | 获取响应的状态消息. 默认情况下, response.message 与 response.status 关联. | |
response.body | 获取响应主体。 | |
response.length | 以数字返回响应的 Content-Length,或者从ctx.body推导出来,或者undefined | |
response.set(field, value) | 设置响应标头 field 到 value | |
response.set(fields) | 用一个对象设置多个响应标头 | |
response.remove(field) | 删除标头 field。 | |
response.type | 获取响应 Content-Type 不含参数 “charset”。 | |
response.redirect(url, [alt]) | 执行 [302] 重定向到 url. |
标题四、路由
1.原生路由
node作为前端服务器,维护多个页面。
可以通过ctx.request.path获取用户请求的路径,由此实现简单的路由。
const Koa = require('koa')
const app = new Koa()
const index = ctx => {
if (ctx.request.path !== '/') {
ctx.response.type = 'html'
ctx.response.body = '<a href="/">Index Page</a>'
} else {
ctx.response.body = 'Hello World'
}
}
app.use(index)
app.listen(3000)
2.koa-router
原生路由始终不方便,可以使用封装好的koa-router。使用起来更为方便
const app = new (require('koa'))()
const router = new (require('koa-router'))()
const other = ctx => {
ctx.response.type = 'html'
ctx.response.body = '<a href="/">Index Page</a>'
}
const index = ctx => {
ctx.response.body = 'Hello World'
}
router.get('/', index)
.get('/other', other)
app.use(router.routes())
app.listen(3000)
效果与原生路由一致。
3、静态资源
一般页面包含各种静态资源(图片、字体、样式、js脚本),逐一写路由非常麻烦
// 静态资源
app.use(koaStatic(path.join(__dirname, '../static')))
4、重定向
有些场合,服务器需要重定向(redirect)访问请求。比如,用户登陆以后,将他重定向到登陆前的页面。ctx.response.redirect()方法可以发出一个302跳转,将用户导向另一个路由。
标题五、中间件
koa最大特色就是中间件(middleware)
再来举个栗子
const index = ctx => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`)
ctx.response.body = 'Hello World'
}
app.use(index)
这段代码可以拆分开
const logger = (ctx, next) => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`)
next()
}
const index = ctx => {
ctx.response.body = 'Hello World'
}
app.use(logger)
app.use(index)
中间件栈
多个中间件会形成一个栈结构,以 先进后出 的顺序执行。
再来个栗子~
const one = (ctx, next) => {
console.log('>> one')
next()
console.log('<< one')
}
const two = (ctx, next) => {
console.log('>> two')
next()
console.log('<< two')
}
const three = (ctx, next) => {
console.log('>> three')
next()
console.log('<< three')
}
app.use(one)
app.use(two)
app.use(three)
本地访问http://127.0.0.1:3000后,命令行输出:
one
two
three
<< three
<< two
<< one
标题六、web app的功能
1.cookies
ctx.cookies用来读写cookie
方法:
ctx.cookies.get读cookie
ctx.cookies.set存cookie
2、表单
本质上表单就是post方法发送到服务器的键值对。koa-bodyparser可以用来从post请求的数据体里面提取键值对
标题七、node koa2常用的中间件
koa-router 路由中间件
koa-bodyparser POST数据处理的中间件
koa-strict 静态资源管理的中间件
koa2 模板引擎(ejs)
koa-views 页面渲染相关的中间件
更多的信息可以移步到官方文档查看:链接: link.