koa 基础(七)错误处理中间件
2023-09-11 14:15:29 时间
1.错误处理中间件
app.js
/** * 错误处理中间件 */ // 引入模块 const Koa = require('koa'); const router = require('koa-router')(); /*引入是实例化路由 推荐*/ // 实例化 let app = new Koa(); // Koa中间件 // 匹配任何路由,如果不写next,这个路由被匹配到了就不会继续向下匹配 // www.域名.com/news app.use(async (ctx, next) => { console.log('这是一个中间件01'); next(); if(ctx.status == 404) { ctx.status = 404; ctx.body = '这是一个 404 页面'; } else { console.log(ctx.url); } }) router.get('/', async (ctx) => { ctx.body = '首页'; }) router.get('/news', async (ctx) => { ctx.body = '这是一个新闻2'; }) router.get('/login', async (ctx) => { ctx.body = '登录页面'; }) app.use(router.routes()); app.use(router.allowedMethods()); /** * router.allowedMethods() 作用:这是官方文档的推荐用法,我们可以 * 看到 router.allowedMethods() 用在了路由匹配 router.routes()之后, * 所以在当所有路由中间件最后调用,此时根据 ctx.status 设置 response 响应头 */ app.listen(3000);
.
相关文章
- 中间件技术及双十一实践·服务框架篇
- ThinkPHP 6.0 管道模式与中间件的实现分析
- 重新整理 .net core 实践篇—————异常中间件[二十]
- 分布式mysql中间件(mycat)
- ThreadX全家桶初探,一旦推广起来,对其它RTOS和中间件几乎是毁灭性打击
- ASP.NET Core应用针对静态文件请求的处理[3]: StaticFileMiddleware中间件如何处理针对文件请求
- SAP CRM中间件Consolidated数据库的实现原理
- 使用SAP CRM中间件从ERP下载Customer的错误消息:Distribution channel is not allowed for sales organization
- 使用中间件从ERP下载SAP sales BOM到CRM
- CRM中间件里parent not ok的错误消息如何处理
- SAP CRM中间件下载出错的错误排查
- ERP Configurable product不会被CRM中间件下载
- java常用中间件处理数据交互、连接数据分离之后两个系统间的通信
- WEB漏洞攻防 - 文件上传漏洞 - 中间件类应用场景 - [VULHUB 靶机]Weblogic任意文件上传漏洞[CVE-2018-2894]
- 1.中间件安全基础(一)
- scrapy 下载器中间件 随机切换user-agent
- 初识中间件Kafka
- 从零实现Web框架Geo教程-中间件-05
- scrapy下载中间件设置代理和useraget大全
- ⭐万字长篇超详细的图解Tomcat中间件方方面面储备知识⭐