In Express or connect with Node.js, is there a way to call another route internally?

前端 未结 2 983
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 13:49

So, I have the setup like this (in Express):

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


        
2条回答
  •  孤独总比滥情好
    2021-01-12 14:34

    Like many things in javascript your original goal can be accomplished with sneakiness. We can overwrite the res.send function so that it doesn't call res.end; this will allow res.send to be called multiple times without issue. Note that this is an ugly, sneaky approach - not recommended, but potentially useful:

    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!');
    
    });
    

提交回复
热议问题