为什么 ctx.redirect 不会阻止代码继续执行

发布于 2025-01-14 23:46:26 字数 557 浏览 2 评论 0原文

我对koa和nodejs中ctx.redirect的功能有点困惑。

try {
  let user = await db.collection("user").findOne({"username":username, "password":password});
  if (!user) ctx.redirect('/error');
  console.log("can run here");
} catch (e) {
  ctx.body = {error:true, msg: e instanceof Error ? e.message : e};
}

我认为如果用户存在,它会打印can run here,相反,如果用户不存在,它不会打印can run here

但如果用户不存在,它仍然打印 can run here,我尝试将代码更改为 if (!user) ctx.redirect('/error'); return;,无论用户存在与否,代码都不会继续执行,不会打印任何内容,为什么?谢谢。

I'm a little confused about the function of ctx.redirect in koa and nodejs.

try {
  let user = await db.collection("user").findOne({"username":username, "password":password});
  if (!user) ctx.redirect('/error');
  console.log("can run here");
} catch (e) {
  ctx.body = {error:true, msg: e instanceof Error ? e.message : e};
}

I thought if the user exists, it will prints can run here, conversely, it will not print can run here if the user does not exist.

But if the user does not exist, it still prints can run here, and I tried change the code to if (!user) ctx.redirect('/error'); return;, the code does not continue to execute whether the user exists or not, nothing will print, why? Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文