koa2 学习路由、中间件、各常用模块

中间件(洋葱模型)、放在中间件中的常用模块
  • 中间件的写法
app.use(async (ctx,next)=>{
	.......
	await next();
	.......
})
  • koa-bodyparser模块,接收post请求传俩的参数
	const bodyparse = require('koa-bodyparser');
	app.use(bodyparse());

	// 获取参数
	const { name } = ctx.request.body;
  • 跨域模块
const cors = require('koa2-cors');
    // 请求头允许跨域
    app.use(cors({
        origin: function (ctx) {
            // if (ctx.url === '/test') {
            //     return "*"; // 允许来自所有域名请求
            // }
            return 'http://localhost:8080';
        },
        exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
        maxAge: 5,
        credentials: true,
        allowMethods: ['GET', 'POST', 'DELETE'],
        allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
    }))
  • koa-static 静态资源中间件
const staticFiles = require('koa-static')
app.use(static('./static'));
  • log日志
const log4js = require('log4js');

const logjs = (app) => {
	app.use(async (ctx,next) => {
		log4js.configure({
			appenders: { cheese: { type: 'file', filename: 'cheese.log' } },
			categories: { default: { appenders: ['cheese'], level: 'error' } }
		}); 
		const logger = log4js.getLogger('cheese');
		// logger.trace('Entering cheese testing');
		// logger.debug('Got cheese.');
		// logger.info('Cheese is Comté.');
		// logger.warn('Cheese is quite smelly.');
		// logger.error('Cheese is too ripe!');
		// logger.fatal('Cheese was breeding ground for listeria.');		
		await next();
	})
}
module.exports = logjs;
  • 状态码处理
    – 返回404页面,node是不会报错的。
    – 利用洋葱模型,将捕获错误码页面,放在最外一层洋葱层,捕获next()里面所有的错误码。
app.use(async (ctx,next)=>{
	try{
		await next();
		if(ctx.response.status === 404 && !ctx.response.body){
			ctx.throw(404);
		}
	}
	catch(err){
	// 捕获判断错误码
		let fileName;
		let status = parseInt(e.status);
		const message = e.message;
		if(status >= 404){
			switch(status){
				case 400:
				case 500:
				case 404:
					fileName = status;
					break;
				default:
					fileName = 'other';					
			}
		}
		ctx.body = fileName;
	}
})
错误处理加日志处理网址
https://blog.csdn.net/qq8344310/article/details/100677139
路由
  • query
router.get('/:id',async (ctx,next) => {
	// ctx.quey;
})
  • params
router.get('/:name/aaa',async (ctx,next) => {
	// ctx.params
})
  • prefix路由前段
const router = new Router({
  prefix: '/users'
});
  • redirect 重定向 ctx.redirect(’/sign’)
ctx.redirect('/sign')
  • status 返回状态码 ctx.status = 200
ctx.status = 200
  • 还没完

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值