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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12737371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:25:01  来源:igfitidea点击:

Calling already defined routes in other routes in Express NodeJS

node.jsexpressrun-middleware

提问by user1148710

I am writing a web app in node.js using Express. I have defined a route as follows:

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

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?

如何从 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?

我在 API 文档中找不到任何内容,我宁愿不使用像“请求”这样的另一个库,因为这看起来很笨拙。我试图让我的应用程序尽可能模块化。想法?

Thanks

谢谢

采纳答案by Gates VP

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.secondService);

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.

老实说,将回调嵌套在里面的整个业务app.get(...)并不是一个很好的做法。您最终会得到一个包含所有核心代码的巨大文件。

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.

您真正想要的是一个包含所有回调处理程序app.get()app.post()语句的文件,这些处理程序位于不同的、组织得更好的文件中。

回答by c0deNinja

Similar to what Gates said, but I would keep the function(req, res){}in your routes file. So I would do something like this instead:

类似于盖茨所说的,但我会将其保留function(req, res){}在您的路线文件中。所以我会做这样的事情:

routes.js

路由.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);
});

And then in your module have your logic split up like so:

然后在您的模块中将您的逻辑拆分如下:

myModule.js

我的模块.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;

回答by Der Hochstapler

If you have a lot of middleware on your route, you can benefit from spreading:

如果你的路线上有很多中间件,你可以从传播中受益:

const router = express.Router();

const myMiddleware = [
    authenticationMiddleware(),
    validityCheckMiddleware(),
    myActualRequestHandler
];

router.get( "/foo", ...myMiddleware );
router.get( "/v1/foo", ...myMiddleware );

回答by Aminadav Glickshtein

You can use run-middlewaremodule exactly for that

您可以run-middleware完全为此使用模块

app.runMiddleware('/firstService/query',function(responseCode,body,headers){
     // Your code here
})

More info:

更多信息:

Disclosure: I am the maintainer & first developer of this module.

披露:我是这个模块的维护者和第一个开发者。

回答by Dhiraj

I have used following way: at userpage.js

我使用了以下方式:在 userpage.js

router.createSitemap = function(req, res, callback) {  code here callback(value);  }

at product.js

在 product.js

var userPageRouter = require('userpages'); 
userPageRouter.createSitemap(req, res, function () {
                            //console.log('sitemap');
                        });

Also can use in same userpage.js router I can use for other routing as well. eg.

也可以在同一个 userpage.js 路由器中使用,我也可以用于其他路由。例如。

router.get('/sitemap', function (req, res, next) {
    router.createSitemap(req, res, function () {
        res.redirect('/sitemap.xml');
    }); });

Hope this will help.

希望这会有所帮助。