不能调用 next() 作为最后一个中间件?



出于某种原因,如果我是最后一个中间件并且我尝试调用next()函数,则会遇到与此常见SO问题相同的错误。

为了让我有一个最小的例子,我设置如下:

在我的路线中,我有:

router.get('/add',(req,res,next) => {
res.render('ideas/add');
next();
});

然后我有最后一个中间件:

app.use(function finalMiddleware(req,res,next){
console.log("We are here!");
console.log(app._router.stack);
next();
});

控制台将以下内容记录为堆栈中的最后一个元素:

Layer {
handle: [Function: finalMiddleware],
name: 'finalMiddleware',
params: {},
path: '',
keys: [],
regexp: { /^/?(?=/|$)/i fast_star: false, fast_slash: true },
route: undefined } ]

但是,我仍然得到:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:471:11)
at ServerResponse.header (../node_modules/express/lib/response.js:767:10)
at ServerResponse.send (../node_modules/express/lib/response.js:170:12)
at done (../node_modules/express/lib/response.js:1004:10)
at Immediate.<anonymous> (../node_modules/express-handlebars/lib/utils.js:26:13)

我想知道这是否与车把有关?我只是不明白为什么如果我不使用更高版本的中间件编写标头,这可能是一个问题。我似乎无法弄清楚如何进一步调试它。当然,我可以从最后一个中间件中删除next()调用,但我想了解是否有更深层次的事情发生,因为我是 Express 的新手,并希望让我正确理解东西。

事实证明,我从类似的答案和我的调查中都缺少一条关键信息:如果调用next()并且没有关于middlware的任何内容可执行,服务器将Cannot GET /(route name)发送一条消息。对我来说,我的回调是在发送此消息后执行的,因为next()必须调用写入此默认响应的函数。

因此,由于 Express 已经Cannot GET /(routename)发送了消息,一旦回调触发,它就无法发送响应。

相关内容

最新更新