在定义koa的路由时,统一处理404,发现在ctx.response之前的status为404,之后的status为200
//koa-router
const index = async (ctx, next) => {
ctx.response.type = 'html';
ctx.response.body = await readPage('index.html');
}
const home = async (ctx, next) => {
console.log(ctx.status);//打印404
ctx.response.type = 'html';
ctx.response.body = await readPage('home.html');
console.log(ctx.status);//打印200
}
router.get('/', index);
router.get('/index', index);
router.get('/home', home);
//使用中间件 处理404
app.use(async (ctx, next) => {
await next();
if(ctx.status === 404 ){
ctx.response.type = 'html';
ctx.response.body = await readPage('404.html');
}
})