Node.js Express-在完成处理整个请求之前提供HTTP响应

Ale*_*lls 5 http node.js express

我有一个Node.js Express服务器,我在其中发送响应,然后尝试对同一请求实例进行更多处理。

如果在发送标头后写入res,将会收到一个错误-但是,如果我在将响应发送回相应的响应之后使用req可读流,会发生什么情况?

换句话说,在完成整个请求处理之前,如何通过Node.server发送HTTP响应?

其他换句话说,如果我已经发回的响应,我怎么能“消费”在已经后请求发送的响应-是不是真的只是一个做任何事情,除了发回一个响应的事?

目前,似乎存在一些与使用与已发送的响应相对应的请求对象(流)有关的奇怪错误。

让我举一些例子,用代码-

下面显示了服务器中的最后3个Express中间件处理程序。作为一个有趣的旁注-一旦为一个请求调用了一个中间件处理程序,就无法重新调用它(看起来是这样)。因此,发生的情况是发送响应时将调用下面的第一个处理程序。然后,另一条执行路径(使用process.nextTick或setImmediate)调用next(),并调用后两个处理程序,这意味着我最终在服务器上登录了404。

app.use(function (req, res, next) {

    var r;

    var timeRequired = (Date.now() - req.request_start) + 'ms';
    console.log("Time required for request:", timeRequired);

    if (r = req.lectalTemp) {
        if (!req.lectalSent) {
            req.lectalSent = true;
            res.status(r.status).json({timeRequired: timeRequired, success: r.data});
        }
        else {
            console.log('Headers sent already, but here is the data that would have been sent:', r);
        }
    }
    else {
        next();
    }

});


// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('404: Not Found - ' + req.method + ' ' + req.originalUrl);
    err.status = 404;
    next(err);
});

app.use(function (err, req, res, next) {

    var timeRequired = (Date.now() - req.request_start) + 'ms';

    if (app.get('env') === 'production') {
        res.status(err.status || 500).json({
            error: 'sorry the API experienced an error serving your priority request'
        });
    }
    else {
        console.error(colors.bgRed(err), '\n', err.stack);

        if (!res.headersSent && !req.lectalSent) {
            req.lectalSent = true;
            res.status(err.status || 500).json({
                error: {
                    timeRequired: timeRequired,
                    errMessage: err.message,
                    errStack: err.stack
                }
            });
        }

    }
});
Run Code Online (Sandbox Code Playgroud)

小智 1

我会用队列解决这个问题。将具有低关键数据的消息发布到队列(例如 RabbitMq 或类似队列),并创建一个异步使用队列中消息的工作线程。

  • 不知道为什么这里需要排队。听起来更像是 OP 只是想在发送响应后继续运行更多代码,这是一件非常好的事情。 (2认同)