记录-如何优雅的使用koa-router进行404拦截
import koa from 'koa'
import { router } from './routers'
const app = new koa()
app.use(router.routes())
app.listen(5024, () => {
console.log('短连接服务启动完成:5024')
})
import Router from 'koa-router'
import { BaseRouter } from './base'
import { ConfigRouter } from './config'
let router = new Router()
router.use('', BaseRouter.routes())
router.use('/config', ConfigRouter.routes())
export { router }
import Router from 'koa-router'
const router = new Router()
router.get('/(.*)', async (_ctx, next) => {
try {
await next()
} catch (error: any) {
_ctx.body = error?.message || '500'
_ctx.status = 500
}
})
router.get('/(.*)', async (_ctx, next) => {
await next()
if (!_ctx.body) {
_ctx.body = '404'
_ctx.status = 404
}
})
export { router as BaseRouter }
import Router from 'koa-router'
const router = new Router()
router.get('/', async (ctx, _next) => {
ctx.body = 'config'
})
router.get('/:id', async (ctx, _next) => {
ctx.body = ctx.params.id
})
export { router as ConfigRouter }


