node.js - 发送响应后,Node/Express 中如何结束当前的请求处理?

标签 node.js express middleware

关于这个问题有一些帖子,但没有一个直接、正面地回答这个问题。让我澄清一下,我理解(或者我认为)next()、next('route')、return next()、return 的使用及其对控制流的影响。 我的应用程序的整个中间件由一系列 app.use 组成,如:

 app.use(f1);
 app.use(f2);
 app.use(f3);
 app.use(f4);
 ...

在这些中间件中的每一个中,我都有可能发送响应并在不需要进一步处理的情况下完成。我的问题是我无法阻止处理转到下一个中​​间件。

我有一个笨拙的解决方法。我只是在发送响应后设置了一个 res.locals.completed 标志。在所有中间件中,一开始,我检查这个标志,如果设置了标志,则跳过中间件中的处理。在第一个中间件中,此标志未设置。

当然,一定有更好的解决方案,是什么?我认为 Express 会隐式地执行此检查并通过某些特定于 express 的方法跳过中间件?

最佳答案

根据 http://expressjs.com/guide/using-middleware.html 上的 express 文档

If the current middleware does not end the request-response cycle,
it must call next() to pass control to the next middleware,
otherwise the request will be left hanging.

因此,如果中间件需要提前结束请求-响应,则不要调用 next(),而是确保中间件通过调用 res.end 真正结束请求-响应res.sendres.render 或任何隐式调用 res.end

的方法
app.use(function (req, res, next) {
  if (/* stop here */) {
    res.end();
  } else {
    next();
  }
});

这是一个示例服务器,显示它可以正常工作

var express = require('express');
var app = express();

var count = 0;
app.use(function(req, res, next) { 
  console.log('f1'); 
  next();
 })
app.use(function(req, res, next) {
  console.log('f2');
  if (count > 1) {
    res.send('Bye');
  } else {
    next();
  }
})
app.use(function(req, res, next) {
  console.log('f3');
  count++;
  next();
})

app.get('/', function (req, res) {
  res.send('Hello World: ' + count);
});

var server = app.listen(3000);

你会看到 3 次请求后,服务器显示“Bye”并且未达到 f3

关于node.js - 发送响应后,Node/Express 中如何结束当前的请求处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33648905/

相关文章:

node.js - 将文件从 Base64 转换并作为二进制文件发送到某些外部服务

javascript - 为什么我的类构造变量在声明后保持未定义状态?

javascript - 当 Node.js 向其他服务器请求长时间的 http 请求时,Node.js 的正确行为是什么

mysql - 共享服务器上的 Rest API

node.js - Passport Node.js 本地身份验证不起作用

javascript - Node.js 事件监听器被阻止?

asp.net-core - ASP.NET Core MVC 实现 SEO 2021

javascript - express js :middleware function is not invoked

asp.net-core-2.0 - 如何编写中间件来测量asp.net core 2.0中请求处理时间

javascript - 异步等待和可共享的 MongoDB 连接