Express:在 json() 之后调用 next() - 中间件

Express: calling next() after json() - Middlewares

使用 NodeJs 和 Express 构建 REST API:我的目标是实现 2 个最简单的 Middlewares

  1. 第一个将记录传入的请求
  2. 第二个将记录处理后的响应(这是一个 JSON

第一个中间件(在app.js)

function logReqMiddleware(req, res, next) {
  log.info('>>> %s at %s', req.method, req.path);
  next();
}

第二个中间件(在app.js)

function logResponseMiddleware(req, res, next) {
  log.info('<<< %s (%s)', JSON.stringify(res), res.status);
  next();
}

控制器函数(在apiController.js)

export var router = express.Router();
router.get('/', foo);

function foo(req, res, next) {
  res.status(200).json({ stupidExample: true });
  next();
}

构建应用程序 (app.js)

var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logReqMiddleware);
app.use('/api', apiController.router);
app.use(logResponseMiddleware);
var server = app.listen(3000, function(){ log.info('running'); });

现在,在 localhost:3000/api 提出请求说:can't set headers after they are sentthis is the related super cool response我的问题是,写json数据和json()加第二个中间件不兼容吗?我该如何解决?

不要在 logResponseMiddleware 中调用 next()。没有别的事可做,所以调用 next() 可能会将您发送到 express 的默认 404 处理程序,该处理程序试图以默认状态和正文进行响应。

旁白:JSON.stringify(res) 不是您想要的。 res 是表示响应的对象实例(很多方法、内部状态属性等)。它不是响应正文内容字符串。由于 res 是一个可写流,它不会保留响应正文内容供您记录,它只会尝试通过 HTTP 连接发送它。