在Express NodeJS中调用其他路由中已定义的路由

use*_*710 30 node.js express run-middleware

我正在使用Express在node.js中编写一个Web应用程序.我已经定义了如下路线:

app.get("/firstService/:query", function(req,res){
    //trivial example
    var html = "<html><body></body></html>"; 
    res.end(html)
});
Run Code Online (Sandbox Code Playgroud)

如何从快递中重用该路线?

app.get("/secondService/:query", function(req,res){
    var data = app.call("/firstService/"+query);
    //do something with the data
    res.end(data);
});
Run Code Online (Sandbox Code Playgroud)

我在API文档中找不到任何内容,宁愿不使用像"请求"这样的其他库,因为这看起来很笨拙.我想尽可能保持我的应用程序模块化.思考?

谢谢

c0d*_*nja 23

与盖茨所说的类似,但我会保留function(req, res){}你的路线文件.所以我会做这样的事情:

routes.js

var myModule = require('myModule');

app.get("/firstService/:query", function(req,res){
    var html = myModule.firstService(req.params.query);
    res.end(html)
});

app.get("/secondService/:query", function(req,res){
    var data = myModule.secondService(req.params.query);
    res.end(data);
});
Run Code Online (Sandbox Code Playgroud)

然后在你的模块中你的逻辑分裂如下:

myModule.js

var MyModule = function() {
    var firstService= function(queryParam) {
        var html = "<html><body></body></html>"; 
        return html;
    }

    var secondService= function(queryParam) {
        var data = firstService(queryParam);
        // do something with the data
        return data;
    }

    return {
        firstService: firstService
       ,secondService: secondService
    }
}();

module.exports = MyModule;
Run Code Online (Sandbox Code Playgroud)


Gat*_* VP 15

你能简单地把它分解成另一个函数,把它放在一个共享点并从那里开始吗?

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.secondService);
Run Code Online (Sandbox Code Playgroud)

老实说,把这个回调嵌入其中的整个业务app.get(...)并不是一个很好的做法.最终得到一个包含所有核心代码的巨型文件.

你真正需要的是充满了一个文件app.get(),并app.post()声明与所有生活在不同的,更好的组织文件中的回调处理.