node.js 在 Express.js 中 res.send() 后退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14709802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:06:00  来源:igfitidea点击:

Exit after res.send() in Express.js

node.jsexpress

提问by Rob Wilkerson

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:

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

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

  // DO OTHER STUFF IF AUTH IS SUCCESSFUL
}

If I read the source code correctly, it shouldend 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?

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

采纳答案by Floby

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

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

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

express 中的每个处理程序都接收 3 个参数(对于基本 http 取消链接 2),它们是req,resnext

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

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

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

如果next使用参数调用,则此参数将被解释为错误,无论该参数的类型如何。

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 thisfor more info on error handling in Express

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

EDIT: As @Baptiste Costacommented, simply calling next()will notcease 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:

编辑:作为@Baptiste科斯塔评论,只是要求next()不会停止当前的执行,但它会调用上的下一个中间件。最好使用它return next()来防止 Node 进一步抛出错误(例如can't set headers after they are sent- 错误)。这包括上述常见的错误抛出建议:

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

回答by Steve Beer

Of course express can not magically make your javascript function stop executing from somewhere else.

当然,express 不能神奇地使您的 javascript 函数停止从其他地方执行。

I don't like the next([error]) solution because I think errors should be only used for circumstances you usually don't expect (like an unreachable database or something). In this case, a simple wrong password would cause an error. It is a common convention to not use exceptions/errors for ordinary control flow.

我不喜欢 next([error]) 解决方案,因为我认为错误应该只用于您通常不期望的情况(例如无法访问的数据库或其他情况)。在这种情况下,一个简单的错误密码就会导致错误。对于普通的控制流,不使用异常/错误是一个常见的约定。

I therefore recommend to place a return statement after the res.send call to make your function stop executing further.

因此,我建议在 res.send 调用之后放置一个 return 语句,以使您的函数停止进一步执行。

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

  // DO OTHER STUFF REALLY ONLY IF AUTH IS SUCCESSFUL
}

回答by Varun

Simply do something like this to stop further execution.

简单地做这样的事情来停止进一步的执行。

function (request, response, next) {
    var path = request.body.path;

    if(path === undefined){
        response.status(HttpStatus.BAD_REQUEST);
        response.send('path is required!');
    }

    next(response)
};

回答by alexalejandroem

You only need to do a return to end the flow:

你只需要做一个 return 来结束流程:

return  res.send( 401 );

That will send the 401 response back and won't proceed forward in the flow.

这将发回 401 响应,并且不会在流程中继续前进。

回答by frank

Why is no-one suggesting using an 'else' block?

为什么没有人建议使用“else”块?

if(!auth){
    // Auth fail code
    res.send 'Fail'
} else {
    // Auth pass code
    res.send 'Pass'
}

'next' is used when creating your own middleware for the "app.use(function(req, res, next));". If you have set up a route like "app.get(route, function(req, res));" then the code in the function is where you can have the code you are specifying without needing to use 'next'.

'next' 用于为“app.use(function(req, res, next));”创建自己的中间件。如果您设置了类似“app.get(route, function(req, res));”的路由 那么函数中的代码是您可以指定代码的地方,而无需使用“下一步”。