koa常用模块基本使用

司徒翼
2023-12-01

koa常用模块

Koa

使用Koa创建服务器

koa核心模块
可以同next来进行异步调用,洋葱模型,由上向下指向结束后,再按顺序由下之上执行

	const Koa = require("koa")
	const app = new Koa()	
	app.use(async (ctx,next)=>{
		ctx.body="inde"
		console.log(1)
		await next()
		console.log(3)
	})
	app.use((ctx)=>{
		console.log(2)
	})
	
	app.listen(3000)
	// 监听3000端口
	

path

path模块包含在node核心模块中

	const path =require("path")
	const publicPath = path.join(__dirname,"路径")

path.join方法可将路径转化为绝对路径

fs

fs模块包含在node核心模块中

	const fs =require("fs")
	let buffer = fs.readFileSync("路径")
	// 可将路径导入文件转为二进制
	let str = buffer.toString()
	// 需转为字符串后使用

logger

logger为日志模块,直接app.use()调用使用,需放在除导入模块代码外的所有代码之前

	const logger = require("koa-logger")
	app.use(logger())

可获取端口上行下行记录

onerror

onerror模块为报错模块,可将服务器报错内容传入网页中显示

	const onerror = require("koa-onerror") 
	onerror(app)
	// 将需要监控的服务传入

router

router 路由模块为构造函数
需先创建router模块后将模块内容到出,再导入到app.js使用

	//router=>index.js
	const Router = require("koa-router")
	const router = new Router()
	// 创建路由对象
	router.get("/",(ctx)=>{
		ctx.body="index"
	})
	// 使用get方法传入两个变量 第一个为字符串为传入的路径,第二个变量为匿名函数,为许需要传入的内容
	module.exports=router
	// 将创建好的路由导出
	
	
	// app.js
	const router = require("./router")
	app.use(router())
	// 在app.js导入router并使用

static

static模块为控制静态资源根目录的模块

	const static = require("koa-static")
	
	app.use(static("路径"))
	// 传入路径为public文件路径
	// 该路径要求为绝对路径,需配合path使用

art-template

art-template为模板引擎

	const template = require("koa-art-template")
	
	template(app,{
		root:path.join(__dirname,"./views"),
		extname:".html"
		debug:true
	})
	// 导入后传入两个参数,第一个是需要监控的服务对象
	// 确认监控对象后将在全局的ctx上挂在art-template的方法
	
	// 第二个参数传入一个对象
	// root 传入需渲染网页的绝对路径,配合path
	// extname 为可省略的文件名后缀e
	//  debug 为开启查错

确认监控对象后将在全局的ctx上挂载art-tmplate的方法

	ctx.render("userlist",{对象})
	// 传入第一个字符串为在已配置的root目录下的文件名自动拼接已经设置的extname后缀名
	// 将对象中的数据渲染值对应文件
	// 使用方法和art-template一致
 类似资料: