koa2 ctx.status 返回值的问题

岁酱吖の 提交于 2019-12-04 06:16:52

在定义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');
  }
})

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!