问题描述
我正在使用Express在node.js中编写一个网络应用程序。我已经定义了一条路线如下: app.get(/ firstService /:query,function(req,res) {
// trivial example
var html =< html>< body>< / body>< / html>;
res.end(html)
});
如何从快递中重用该路由?
app.get(/ secondService /:query,function(req,res){
var data = app.call(/ firstService /+ query );
//使用数据
res.end(data);
}执行某些操作;
我在API文档中找不到任何东西,宁可不使用其他库,如请求因为这似乎是坏蛋。我试图让我的应用程序尽可能模块化。想想?
谢谢
另一个功能是把它放在一个共享的位置,然后从那里去?
var queryHandler = require('special_query_handler');
//包含一个名为firstService(req,res)的方法;
app.get('/ firstService /:query',queryHandler.firstService);
//第二个app
app.get('/ secondService /:query',queryHandler.firstService);
老实说,这个整个业务将回调嵌套在应用程序之内。 get(...)
并不是一个很好的做法。你最终得到一个包含所有核心代码的巨型文件。
你真正想要的是一个填充有的文件app.get()
和 app.post()
所有回调处理程序的语句生活在不同的更好的组织文件中。
I am writing a web app in node.js using Express. I have defined a route as follows:
app.get("/firstService/:query", function(req,res){
//trivial example
var html = "<html><body></body></html>";
res.end(html)
});
How do I reuse that route from within express?
app.get("/secondService/:query", function(req,res){
var data = app.call("/firstService/"+query);
//do something with the data
res.end(data);
});
I couldn't find anything in the API documentation and would rather not use another library like "request" because that seems kludgey. I am trying to keep my app as modular as possible. Thoughts?
Thanks
Can you simply break this out into another function, put it in a shared spot and go from there?
var queryHandler = require('special_query_handler');
// contains a method called firstService(req, res);
app.get('/firstService/:query', queryHandler.firstService);
// second app
app.get('/secondService/:query', queryHandler.firstService);
Honestly, this whole business of nesting the call back inside of the app.get(...)
is not really a great practice. You end up with a giant file containing all of the core code.
What you really want is a file filled with app.get()
and app.post()
statements with all of the callback handlers living in different, better organized files.
这篇关于调用Express NodeJS中其他路由中已定义的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!