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

查看:313
本文介绍了在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
}

如果我正确读取源代码,它应该结束请求(中止进一步处理)但是我是新来的节点,所以我还没有准备好相信我正在阅读什么,要想把它烧掉,我想我主要是从一个更值得信赖的来源寻找一个确定的答案,即我自己的解释不熟悉的源代码,如果 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的链接2),它们是 req res next

Each handler in express receives 3 parameters (unlinke 2 for basic http) which are req, res and 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])。当下一个被调用错误时,而不是调用中间件链中的下一个处理程序,它调用错误处理程序。您应该处理该错误处理程序中的401响应代码。有关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

编辑:As @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]));

[我的歉意不发表评论,还没有足够的声誉] em>

[My apologies for not posting this in a comment, not enough reputation yet]

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

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