在 Express.js 中 res.send() 后退出 [英] Exit after res.send() in Express.js

查看:46
本文介绍了在 Express.js 中 res.send() 后退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当简单的 Express.js 应用程序,其中包含一个登录组件,如果登录失败,我想提前退出.我看到有迹象表明应用程序没有这样做,而且我还没有找到明确的答案来表明调用 res.send() 是否会停止任何进一步的处理.这是我现在的代码:

I have a fairly simple Express.js app with a login component that I'd like to exit early if login fails. I'm seeing indications that the app isn't doing that and I haven't found a definitive answer that indicates whether calling res.send() halts any further processing. Here's my code as it stands now:

client.login( username, password, function( auth, client ) {
  if( !auth ) {
    res.send( 401 );
  }

  // DO OTHER STUFF IF AUTH IS SUCCESSFUL
}

如果我正确阅读了源代码,它应该结束请求(中止进一步处理),但我是 node 的新手,所以我还没有准备好相信我的想法正在阅读.归根结底,我想我主要是从更值得信赖的来源中寻找明确的答案,而不是我自己对不熟悉的源代码的解释.如果 send() 没有中止处理,那么正确的方法是什么?

If I read the source code correctly, it should end the request (aborting further processing), but I'm new to node, so I'm not quite ready to trust what I think I'm reading. To boil it down, I guess I'm mostly looking for a definitive answer from a more trustworthy source that my own interpretation of unfamiliar source code. If send() doesn't abort processing, what's the right way to do that?

推荐答案

如果你使用 express 作为你的框架,你应该调用 next() 代替.

If you are using express as your framework, you should call next() instead.

express 中的每个处理程序接收 3 个参数(基本 http 的 unlinke 2),它们是 reqresnext

Each handler in express receives 3 parameters (unlinke 2 for basic http) which are req, res and next

next 是一个函数,当不带参数调用时将触发中间件链中的下一个处理程序.

next is a function that when called with no arguments will trigger the next handler in the middleware chain.

如果使用参数调用 next,则无论该参数的类型如何,该参数都会被解释为错误.

If next is called with an arguments, this argument will be interpreter as an error, regardless of the type of that argument.

它的签名是next([error]).当 next 被错误调用时,它不会调用中间件链中的下一个处理程序,而是调用错误处理程序.您应该在该错误处理程序中处理 401 响应代码.请参阅this了解有关 Express 中错误处理的更多信息

Its signature is next([error]). When next is called with an error, then instead of calling the next handler in the middleware chain, it calls the error handler. You should handle the 401 response code in that error handler. See this for more info on error handling in Express

正如 @Baptiste Costa 评论的那样,只需调用 next()不会停止当前执行,但它会调用下一个中间件.最好使用 return next() 来防止 Node 进一步抛出错误(例如 发送后无法设置标头 - 错误).这包括上述常见的错误抛出建议:

As @Baptiste Costa commented, simply calling next() will not cease the current execution but it will call on the next middleware. It is good practice to use return next() instead to prevent Node from throwing errors further on (such as the can't set headers after they are sent - error). This includes the above suggestion of error throwing which is common:

return next(new Error([error]));

这篇关于在 Express.js 中 res.send() 后退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆