express.js res.sendFile可以';t在发送邮件后设置邮件头

express.js res.sendFile可以';t在发送邮件后设置邮件头,express,Express,我有以下代码: app.use(function (req, res, next) { // res.sendfile(__dirname + '/forms.html'); try { // serve html snapshot res.sendFile(__dirname + '/forms.html'); } catch (err) { // no snapshot available, serve 404 er

我有以下代码:

app.use(function (req, res, next) {  
    // res.sendfile(__dirname + '/forms.html');
    try {
        // serve html snapshot
        res.sendFile(__dirname + '/forms.html');
    } catch (err) {
        // no snapshot available, serve 404 error
        res.send(404);
    } 
    return next();
});           
但在运行时出现以下错误:

Error: Can't set headers after they are sent.
    at SendStream.headersAlreadySent (/local/home/admin-gst/web/test/lza/node_modules/express/node_modules/send/index.js:326:13)
    at SendStream.send (/local/home/admin-gst/web/test/lza/node_modules/express/node_modules/send/index.js:525:17)
    at onstat (/local/home/admin-gst/web/test/lza/node_modules/express/node_modules/send/index.js:624:10)
    at FSReqWrap.oncomplete (fs.js:82:15)

有人能帮忙吗?

因为你的app.use没有指定路由,所以每次请求都会调用它。如果被击中的路线也试图发送响应(我假设这是基于错误发生的情况),例如

您将收到此错误,因为响应已在中间件中发送


您需要在路由中执行res.sendFile,而不是在中间件中执行,或者只有在中间件不发送响应时才有条件地调用next(),这样执行才会在中间件处停止。

不清楚您在做什么。请张贴完整的代码是的,你是对的。但我的问题是如何在中间件中集成表单,当表单提交时,我希望自动转到下一个中间件。这不是您所问的问题。你应该结束这个问题,然后发布一个新的问题,更详细地说明你想要完成什么。
app.get('/someRoute', function(req, res) {res.send('success');});