node middleware-koa framework

1. Basic use of koa

  • Installnpm i koa
  • What koa exports is a class, which must newbe created using keywords
  • Koa also completes request operations by registering middleware
const koa = require('koa');
//  导出的类,必须用new关键字
const app = new koa()
app.listen(8000, () => {
    
    
	console.log('koa 服务器启动~')
})

//  使用koa这里传递两个参数 cxt 与next
app.use((cxt, next) => {
    
    
	console.log('匹配中间')
	cxt.body = '使用cxt中的body返回数据'
})

2. Parameter analysis

  • The middleware registered by koa provides two parameters:
  • ctx: context object;
    • Koa does not separate req and res like express, but uses them as attributes of ctx;
    • ctx represents the context object of a request;
    • ctx.request: Get the request object;
    • ctx.response: Get the response object;
  • next: essentially a dispatch, similar to the previous next;

注意点

  1. cxtThe context has a request object, one is request既koa本身的对象, and anothernode 封装的请求对象:req
  2. Two response objects:cxt.response 是koa封装的响应式对象 ,txt.res 是node封装的响应式对象
app.use((cxt, next) => {
    
    
	 /**  注意点 两个请求对象
	 * @description:  cxt 上下文有两个请求对象一个是request既koa本身的对象,还有一个node封装的请求对象:req
	 * @param {type} 
	 */
	cxt.request   // 
  cxt.req
	/** 响应对象 两个响应对象
	* @description:  cxt.response 是koa封装的响应式对象
	* @param {type} txt.res 是node封装的响应式对象
	* @return: 
	*/
	cxt.body = '使用cxt中的body返回数据'
})

3. Request path distinction

  • Through the app object created by koa, the middleware can only be registered through the use method:
    • Koa does not providemethods的方式来注册中间件;
    • Neither 提供path中间件来匹配路径;
  • But how do we separate paths and methods in development?
    • Method 1: 根据request自己来判断;
    • Method 2: 使用第三方路由中间件;
// path
// app.use((cxt, next) => {
    
    
// 	if (cxt.path === '/users') {
    
    
// 	} else if (cxt.path === '/login') {
    
    
// 		cxt.body = '登录成功'
// 	} else { }
// })

// method 
app.use((cxt, next) => {
    
    
	if (cxt.method === 'POST') {
    
    
		cxt.body = '登录成功'
	} else {
    
     }
})

4. Routing

  • Installnpm install @koa/router
const koa = require('koa');
const router = require('@koa/router')


const app = new koa()
// 1. 安装路由使用  npm i @koa/router

const userRouter = new router({
    
     prefix: '/users' })
//2. 注册路由中间件
userRouter.get('/', (cxt, next) => {
    
    
	cxt.body = '路由使用'
})

userRouter.get('/:id', (cxt, next) => {
    
    
	const id = cxt.params.id
	console.log(id);
	cxt.body=id
})

// 3. 路由生效  
app.use(userRouter.routes())
// allowedMethods路径或者方法匹配配置
app.use(userRouter.allowedMethods())
app.listen(8000, () => {
    
    
	console.log('koa 服务器启动~')
})

Note :allowedMethods用于判断某一个method是否支持:某个请求或者路径是否正确

5 Parameter analysis

  1. get params method example:/:id
  2. Example of get query method:?name=admin&age=18
  3. post json method example{name:"admin" pass:123456}
  4. post x-www-form-urlencoded
  5. post form-data
  • 注意点The following routes are uniformly registered asusers
const userRouter = new router({
    
     prefix: '/users' })

5.1 params and query parsing

  • params parametercxt.params.id
  • query parametercxt.query
 userRouter.get('/:id', (cxt, next) => {
    
    
 	const id = cxt.params.id
 	cxt.body = id
 })
 userRouter.get('/', (cxt, next) => {
    
    
 	const query = cxt.query
 	cxt.body = query
 })

5.2 Body parameters and urlencoded analysis

  • Install dependencies:npm install koa-bodyparser;
  • Use and register the koa-bodyparser middleware;app.use(bodyparser())
// 3. post/json  body参数
// 安装库  npm install koa - bodyparser
// app.use(bodyparser())
// userRouter.post('/', (cxt, next) => {
    
    
// 	 const body= cxt.request.body
// 	 cxt.body=body
// })

// 4. urlencoded
app.use(bodyparser())
userRouter.post('/', (cxt, next) => {
    
    
	const body = cxt.request.body
	cxt.body = body
})

5.3 form-data parameter

  • To parse the data in the body, you need to use multer
  • Install dependencies:npm install --save @koa/multer multer
const upload =multer({
    
    })
app.use(upload.any())
app.use((cxt,next)=>{
    
    
	console.log(cxt.req.body);
})

6. File upload

Specific configuration reference

const koa = require('koa');
const router = require('@koa/router')

const multer = require('@koa/multer')
const app = new koa()

app.listen(8000, () => {
    
    
	console.log('koa 服务器启动~')
})

const userRouter = new router({
    
     prefix: '/users' })
/**
 * 5. post form-data 
*/
let storage = multer.diskStorage({
    
    
	destination: (req, file, cb) => {
    
    
		cb(null, './uploads/')
	},
	filename: (ctx, file, cb) => {
    
    
		cb(null, file.originalname);
	}
});

const upload = multer({
    
    
	storage
})

userRouter.post('/', upload.single('file'), (cxt, next) => {
    
    

})
// 5. form-data 解析  需要使用multer
app.use(userRouter.routes())

7. Static server

  • Koa does not have built-in deployment-related functions, so you need to use a third-party library:
  • Install dependenciesnpm install koa-static
const static=require("koa-static")
const app = new koa()
app.use(static('./upload'))

8 response data

  • Response result: body sets the response body to one of the following:
    • string :string data
    • Buffer:Buffer data
    • Stream: streaming data
    • Object|| Array:object or array
    • null :output nothing
    • if response.status尚未设置,Koa会自动将状态设置为200或204.
const userRouter = new router({
    
     prefix: '/users' })
userRouter.post('/', (cxt, next) => {
    
    
	// 1.buffer 响应数据
	// cxt.body=Buffer.from('hello node')
	//  2. 文件流
	// const readerStream = fs.createReadStream('./upload/th5TYWK266.jpg')
	// cxt.type = 'image/jpeg'   // 请求展示图片
	// cxt.body = readerStream
	// 3.响应数组或者对象类型
    cxt.body={
    
    
			name:'admin',
			password:123456
		}
})

9 Error handling

  • When doing unified encapsulation of error handling:cxt上下文可以触发一个emit事件
  • Therefore, you can use app.onto listen for events
const koa = require('koa');
const router = require('@koa/router')
const app = new koa()
app.listen(8000, () => {
    
    
	console.log('koa 服务器启动~')
})
const userRouter = new router({
    
     prefix: '/users' })

userRouter.get('/', (cxt, next) => {
    
    
	const isAuth = false
	if (isAuth) {
    
    
		cxt.body = '登录成功,返回token'
	} else {
    
    
		// cxt.body = {
    
    
		// 	code: 1001,
		// 	message: '没有进行授权'
		// }
		// 统一处理错误
		cxt.app.emit('errorEvent', 1001,cxt)
	}
})


app.on('errorEvent', (code,cxt) => {
    
    
	let message = ''
	switch (code) {
    
    
		case 1001:
			message = '没有授权'
			break
		default: 1002
			message = '成功'
	}
	const body = {
    
    
		code,
		message
	}
	cxt.body=body
})
app.use(userRouter.routes())

Guess you like

Origin blog.csdn.net/weixin_46104934/article/details/131875165