当前位置:网站首页>Basic usage of Koa framework
Basic usage of Koa framework
2022-07-31 07:02:00 【 K 】
前言(来自官网)
ES6/7 带来的变革
自ES6确定和ES7的async/await开始普及,node.jsdevelopment has become more rapid,可以预见到JavaScriptModerately“头疼”Multiple levels of nested callbacks(注意是”多层嵌套回调“)将会使用Promise + async/await的方式逐渐替代(不是完全替代,Multi-layer nested callbacks also have their special application scenarios).koa2 The trend of the future
基于async/awaitrealize the intermediate systemkoa2The frame will benode.js webThe development direction of the general trend of the popular framework.基于generator/yield的koa1will be gradually removedkoa2替代,毕竟使用co.js来处理generatorIt's a way of transition,Although it has its specific application scenarios,但是用async/awaitSynchronous writing will be implemented more elegantly.
一、Koa是什么?
Koa2 是基于 node.js web serve 框架
koaThe registered middleware provides two parameters,即ctx/next.ctx是req和res的集合;next()is to execute the next middleware.
二、Koa的安装
1.项目初始化
npm init -y // 生成package.json文件
2.安装Koa2
npm install koa --save
3.Hello world
const Koa = require('koa') // 导入Koa
const app = new Koa() // 实例化app对象
app.use( async ( ctx ) => { // 编写中间件
ctx.body = 'Hello world'
})
app.listen(3000) // 启动服务
console.log('[demo] start-quick is starting at port 3000')
4.启动Demo
node index.js // 访问http:localhost:3000
三、中间件
A process-independent business module,可扩展、可插拔.简单来说,It is to split complex business into independent functions,就是中间件.
包含但不限于:
1、npm install koa-router 路由库
const Koa = require('koa');
const Router = require('koa-router'); // 导入koa-router中间件
const app = new Koa();
const userRouter = new Router({
prefix: '/user' }); // 属性前缀
userRouter.get('/test', (ctx, next) => {
ctx.response.body = "test request"
// console.log(ctx.params.id)
});
userRouter.post('/', (ctx, next) => {
ctx.response.body = "test response"
});
app
// .use((ctx, next) => {
// ctx.body = ctx.request.query
// })
.use(userRouter.routes()) //注册为中间件
.use(userRouter.allowedMethods()) //用于判断某一个 method 是否支持,Method Not Allowed
app.listen(3000, () => {
console.log("dome is start")
})
获取params参数:
userRouter.get('/test/:id', (ctx, next) => {
ctx.response.body = "test request"
console.log(ctx.params.id)
});
获取query参数:
.use((ctx, next) => {
ctx.body = ctx.request.query
})
实现二级路由:
const Koa = require('koa')
const fs = require('fs')
const app = new Koa()
const Router = require('koa-router')
let home = new Router()
// 子路由1
home.get('/', async ( ctx )=>{
let html = ` <ul> <li><a href="/page/helloworld">/page/helloworld</a></li> <li><a href="/page/404">/page/404</a></li> </ul> `
ctx.body = html
})
// 子路由2
let page = new Router()
page.get('/404', async ( ctx )=>{
ctx.body = '404 page!'
}).get('/helloworld', async ( ctx )=>{
ctx.body = 'helloworld page!'
})
// 装载所有子路由
let router = new Router()
router.use('/', home.routes(), home.allowedMethods())
router.use('/page', page.routes(), page.allowedMethods())
// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000, () => {
console.log('[demo] route-use-middleware is starting at port 3000')
})
2、npm install koa-bodyparser 解析json数据
const Koa = require('koa')
const bodyParser = require('koa-bodyparser') // 导入koa-bodyparser中间件
const app = new Koa()
app.use(bodyParser()) // 使用ctx.body解析中间件
app.use(async (ctx) => {
if (ctx.url === '/' && ctx.method === 'GET') {
const html = ` <form method="POST" action="/"> <label for="forName" >Name</label> <input id="forName" type="text" name="name"></input> <button type="submit">submit</button> </form> `
ctx.body = html
} else if (ctx.url === '/' && ctx.method === 'POST') {
ctx.body = ctx.request.body //关键句,koa-bodyparser解析POST表单里的数据,为json类型
} else {
ctx.body = "<h1>404 Not Found</h1>"
}
})
app.listen(3000)
console.log('[demo] start-quick is starting at port 3000')
四、洋葱模式
在洋葱模型中,当我们执行第一个中间件时,Love first,然后调用next(),那么此时它会等第二个中间件执行完毕才会继续执行第一个中间件.然后执行第二个中间件,输出我,调用next(),执行第三中间件,输出中.此时第三个中间件执行完毕,返回到第二个中间件,Export China,然后返回到第一个中间件,输出!.
// 1. 导入koa包
const Koa = require('koa')
// 2. 实例化对象
const app = new Koa()
// 3. 编写中间件
app.use((ctx, next) => {
console.log('爱')
next()
console.log('!')
})
app.use((ctx, next) => {
console.log('我')
next()
console.log('华')
})
app.use((ctx) => {
console.log('中')
})
// 4. 监听端口, 启动服务
app.listen(3000)
console.log('server is running on http://localhost:3000')
总结
以上就是今天要讲的内容,本文仅仅简单介绍了Koa的基本使用,koaMany other powerful middlewares are also provided,Allows us to develop quickly and easily.
边栏推荐
猜你喜欢
随机推荐
Oracle入门 07 - Linux 操作系统安装配置(REHL 7.x)
自动化测试之unittest框架
DOM-DOM的介绍以及通过方法获取元素
什么是浮动?什么是文档流?清除浮动的几种方式及原理?什么是BFC,如何触发BFC,BFC的作用
第一次实践——计算器
Oracle入门 04 - Vmware虚拟机安装配置
uni-app生命周期
成员内部类使用方式(工作)
定义一个类,super的使用,私有属性
Oracle入门 05 - VirtualBox的虚拟机安装配置
定位元素之后操作对象
OSI七层模型
LVM和磁盘配额
10.0 堆体系结构概述之元空间/永久代
编辑时过滤当前节点及根据限制的层数过滤数据
ES6-Map和Set
简单计算器,单层循环输出乘法表,字符串方法的使用,格式化输出
Debian 搭建 WireGuard 服务端
svn冲突产生原因
What is float?What is document flow?Several ways and principles of clearing floats?What is BFC, how to trigger BFC, the role of BFC