The consequences of not calling next() in restify

邮差的信 提交于 2019-12-08 15:02:44

问题


I've been using Restify for some time now. I ran across some code that lacks next() and it occurred to me that I'm not sure if I fully understand the reason why next() should be called after res.send(). I get why would use it in a middleware situation, but for a normal route why is it needed? For example:

server.get('/a/:something/',function(req,res,next) {
    res.send('ok');
});

vs

server.get('/b/:something/',function(req,res,next) {
    res.send('ok');
    return next();
});

If return next(); is left out of the code it seems to not cause errors and works from what that I can see.


回答1:


The restify API Guide has this to say:

You are responsible for calling next() in order to run the next handler in the chain.

The 'chain' they are referring to is the chain of handlers for each route. In general, each route will be processed by multiple handlers, in a specific order. The last handler in a chain does not really need to call next() -- but it is not safe to assume that a handler will always be the last one. Failure to call all the handlers in a chain can result in either serious or subtle errors when processing requests.

Therefore, as good programming practice, your handlers should always call next() [with the appropriate arguments].




回答2:


Another issue (currently) is that the Server after event is not emitted if all handlers don't call next. For example, if you are using auditLogger to log requests using the after event, you won't get logs for any requests that reach a handler that doesn't call next.

I have opened a PR to fix the issue so that the after event is emitted either way, but calling next is the expected norm for apps using restify.



来源:https://stackoverflow.com/questions/22354850/the-consequences-of-not-calling-next-in-restify

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!