如何停止中间件链? [英] how to stop middleware chain?

查看:72
本文介绍了如何停止中间件链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果出现错误,如何正确终止中间件链?

How can I properly end a middleware chain in case of error ?

在我的代码中,我有

    if (someProblem) {
        res.status(statuscode).json({message: 'oops'});
        return;
    }

然而,链中的中间件在不断被调用后却给了我Can't set headers after they are sent错误.

Yet the midleware in the chain after that keeps getting called giving me the Can't set headers after they are senterror.

推荐答案

中间件不能自行升级.仅当您调用next()时,它才转到链中的下一步,只要您不调用next(),则下一步将不会执行.

Middleware does not advance on its own. It only goes to the next step in the chain when you call next() so as long as you don't call next(), then the next step will not execute.

因此,如果您只是发送响应并返回(而不调用next()),那么您应该不会有问题.

So, if you just send a response and return (without calling next()), then you should not have an issue.

您在问题中显示的代码本身不会导致您所引用的错误消息,因此必须继续进行更多操作,以确保您不会向我们显示该错误.

The code you show in your question would not, all by itself, cause the error message you refer to so there must be more going on that you aren't showing us for that error to occur.

这篇关于如何停止中间件链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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