在Express或与Node.js连接时,是否有内部调用另一个路由的方法? [英] In Express or connect with Node.js, is there a way to call another route internally?

查看:371
本文介绍了在Express或与Node.js连接时,是否有内部调用另一个路由的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.send('Good2'); });

如果我想使一个聚合函数调用 / mycall1 / mycall2 不重写代码并重新使用 / mycall1 mycall2

What if I want make an aggregate function to call /mycall1 and /mycall2 without rewriting code and reusing code for /mycall1 and /mycall2?

例如:

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


推荐答案

不,没有重写或重构您的码。原因是 res.send 实际调用<$完成写作后,c $ c> res.end 。这样可以结束响应,没有更多的东西可以写。

No, this is not possible without rewriting or refactoring your code. The reason is that res.send actually calls res.end after it is done writing. That ends the response and nothing more can be written.

如你所暗示的那样,您可以通过重构代码来实现所需的效果,以便 / mycall1 / mycall2 内部调用单独的函数, / myAggregate 调用这两个函数

As you hinted to, you can achieve the desired effect by refactoring the code so that both /mycall1 and /mycall2 call separate functions internally, and /myAggregate calls both the functions.

在这些函数中,您必须使用 res.write 来防止结束响应。 / mycall1 / mycall2 / myAggregate 每个都必须单独调用 res.end 实际结束响应。

In these functions, you would have to use res.write to prevent ending the response. The handlers for /mycall1, /mycall2, and /myAggregate would each have to call res.end separately to actually end the response.

这篇关于在Express或与Node.js连接时,是否有内部调用另一个路由的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆