CNode

请教一个Koajs的不知道算不算初级的问题:如果不用throw,怎样手动发送response?

问答
Mmedmin发布于7 年前最后回复7 年前6 回复4005 浏览0 收藏

比如有这样的代码:

 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)

T
TimLiu1#1·7 年前

return 或则else

T
TimLiu1#2·7 年前

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

M
medmin#3·7 年前
引用 TimLiu1let user = await db.User.findOne({....}); if (!user){ ctx.status = 404; ctx.body = "Not Found" }...

@TimLiu1 是加个return即可?

.....
 if (!user){
   		ctx.status = 404;
   		ctx.body = "Not Found";
		return; // 加这一行?
 }
.....
T
TimLiu1#4·7 年前

可以

T
TimLiu1#5·7 年前

就是不要往后执行

M
medmin#6·7 年前
引用 TimLiu1就是不要往后执行

@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()
参与回复
登录后即可参与回复。登录