请教一个Koajs的不知道算不算初级的问题:如果不用throw,怎样手动发送response?
发布于 5 年前 作者 medmin 3387 次浏览 来自 问答

比如有这样的代码:

 let user = await db.User.findOne({....});
 if (user){
           ctx.status = 200;
   		ctx.body = "Hello"
}else{ 
   		ctx.status = 404;
   		ctx.body = "Not Found"
 }

那,可否改为这样的:

 let user = await db.User.findOne({....});
 if (!user){
   		ctx.status = 404;
   		ctx.body = "Not Found"
 }
 ctx.status = 200
 ctx.body = "Hello" 

这样即便user 404了,最后得到的还是200,所以请教大侠:怎样让ctx.status是404? 我记得express有个res.end()的api,不知道koa有没有类似的?查了半天,没找到。谢谢

6 回复

return 或则else

let user = await db.User.findOne({…}); if (!user){ ctx.status = 404; ctx.body = “Not Found” }else{ ctx.status = 200 ctx.body = “Hello” }

@TimLiu1 是加个return即可?

.....
 if (!user){
   		ctx.status = 404;
   		ctx.body = "Not Found";
		return; // 加这一行?
 }
.....

就是不要往后执行

@TimLiu1 好的,谢谢 这下面是koa文档,写的就不要用res.end(),故有此问。 感谢!

//ctx.res
//Node's response object.

//Bypassing Koa's response handling is not supported. Avoid using the following node properties:

res.statusCode
res.writeHead()
res.write()
res.end()
回到顶部