0

So I understand that Node.js Connect works like a stack through which it runs, starting from the top and going to the bottom. From the Connect introduction by its author at http://howtonode.org/connect-it it shows an example like

var Connect = require('connect');

module.exports = Connect.createServer(
  require('./log-it')(),
  require('./serve-js')()
);

The article reads

Every request enters the onion at the outside and traverses layer by layer till it hits something that handles it and generates a response. In Connect terms, these are called filters and providers. Once a layer provides a response, the path happens in reverse.

I'm particulary curious about "Once a layer provides a response, the path happens in reverse". How does that happen? Every middleware gets called again, but in reverse order?

4

1 回答 1

1

不,它们不会再次被反向调用,但是每个中间件都有机会对请求方法进行猴子修补并劫持它们。这并不理想。

// basic logger example
module.exports = function () {
  return function logger(req, res, next) {
    var writeHead = res.writeHead;
    res.writeHead = function (code, headers) {
      console.log(req.method, req.url, code);
      res.writeHead = writeHead;
      return res.writeHead(code, headers);
    };
    next();
  };
};

现在,此代码存在问题,因为 writeHead 不是设置状态代码的唯一方法,因此它不会捕获所有请求。但这是中间件可以在出路时捕获事件的基本方式。

于 2013-04-23T13:24:17.173 回答