【问题标题】:In Express or connect with Node.js, is there a way to call another route internally?在 Express 或连接 Node.js 中,有没有办法在内部调用另一个路由?
【发布时间】:2012-03-17 12:04:27
【问题描述】:

所以,我有这样的设置(在 Express 中):

app.get('/mycall1', function(req,res) { res.send('Good'); });
app.get('/mycall2', function(req,res) { res.send('Good2'); });

如果我想创建一个聚合函数来调用 /mycall1/mycall2 而不重写代码并重用 /mycall1/mycall2 的代码?

例如:

app.get('/myAggregate', function (req, res) {
  // call /mycall1
  // call /mycall2  
});

【问题讨论】:

  • 是的,我在第一行提到过。 :)

标签: node.js routes express


【解决方案1】:

不,如果不重写或重构代码,这是不可能的。原因是res.send actually calls res.end after it is done writing。这样就结束了响应,不能再写什么了。

正如您所暗示的,您可以通过重构代码来达到预期的效果,以便/mycall1/mycall2 在内部调用不同的函数,而/myAggregate 调用这两个函数。

在这些函数中,您必须使用res.write 来防止结束响应。 /mycall1/mycall2/myAggregate 的处理程序必须分别调用 res.end 才能真正结束响应。

【讨论】:

  • 感谢您的确认。没关系..我只需要编写更多代码。大声笑:
【解决方案2】:

就像 javascript 中的许多事情一样,您的最初目标可以通过偷偷摸摸来实现。我们可以覆盖res.send函数,使其不调用res.end;这将允许res.send 被多次调用而不会出现问题。请注意,这是一种丑陋的、偷偷摸摸的方法 - 不推荐,但可能有用:

app.get('myAggregate', (req, res) => {
  // Overwrite `res.send` so it tolerates multiple calls:
  let restoreSend = res.send;
  res.send = () => { /* do nothing */ };

  // Call mycall1
  req.method = 'GET';
  req.url = '/mycall1';
  app.handle(req, res, () => {});

  // Call mycall2
  req.method = 'GET';
  req.url = '/mycall2';
  app.handle(req, res, () => {});

  // Restore `res.send` to its normal functionality
  res.send = restoreSend;

  // Finally, call `res.send` in conclusion of calling both mycall1 and mycall2
  res.send('Good AND Good2!');

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2020-02-03
    相关资源
    最近更新 更多