简体   繁体   English

Express js根据路线需要不同的模块

[英]Express js require different module based on route

I have an app I am trying to mount in express using app.use , such as: 我有一个正在尝试使用app.use挂载在Express中的应用程序,例如:

app.use(require('./foo'));

This will return the app in the sibling file foo.js when defined as such: 定义如下时, foo.js在同级文件foo.js返回该应用程序:

var router = require('express').Router({ mergeParams: true });
module.exports = router;
router.get('/', function (req, res) { 
   res.send(200);
}

// Navigate to /foo  ->  200 ok! 

However, I would like to reference a different app based on the request path, so that instead of 但是,我想根据请求路径引用一个不同的应用程序,以便代替

app.use(require('./foo'));

We could do 我们可以做

app.use(function (req, res) {
    require(req.path);
};

So if there was some file bar.js , we could conceivably 因此,如果有一些文件bar.js ,我们可以想像

// Navigate to /bar 
returns bar app. 

But this does not work, and instead times out, as I believe it is not mounting the required app correctly. 但这不起作用,而是超时,因为我认为它没有正确安装所需的应用程序。 How can I pass a callback to app.use that can mount a required app that is defined in the callback's function definition? 如何将回调传递给app.use ,可以挂载回调函数定义中定义的必需应用程序?

Thanks for any help. 谢谢你的帮助。

A few things to consider here : 这里要考虑的几件事:

1) You will need to call the router itself (which is a (req, res) function like any middleware) and pass it your request. 1)您将需要调用路由器本身(这是(req, res)函数,就像任何中间件一样)并将其传递给您。

app.use(function (req, res) {
    var router = require('.' + req.path); // or whatever your lookup method looks like
    router(req, res);
});

2) Since the main middleware above isn't mounted on any path, req.path will stay the same (eg '/foo' ) and will never match the child router's .get('/') route. 2)由于上面的主要中间件没有安装在任何路径上,因此req.path将保持不变(例如'/foo' ),并且永远不会与子路由器的.get('/')路由匹配。 You can work around this by rather having the child router .use() its middleware, which is fine as you are already in an application endpoint. 您可以通过将子路由器.use()用作中间件来解决此问题,因为您已经在应用程序端点中,这很好。 (Note that if your middleware is simple enough you could also just export the middleware itself rather than the whole router) (请注意,如果您的中间件足够简单,您也可以只导出中间件本身,而不是整个路由器)

// foo.js
router.use(function (req, res) {
    res.send(200);
});

Check out the documentation for Express req.path. 请查看Express req.path的文档。

http://expressjs.com/en/api.html http://expressjs.com/en/api.html

It looks like req.path will return something like /foo , but you need it to be ./foo for it to find the file and require it. 看起来req.path将返回类似/foo ,但是您需要为./foo才能找到文件并需要它。 Try changing your require to be 尝试更改您的要求

require('.' + req.path);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM