在我的快速应用程序中,我有多条不同前缀的路径。每个前缀的路由在单独的文件中定义。
const routes = require('./server/routes');
app.use('/api', routes.apirouter);
app.use('/', routes.webrouter);其中‘./server/ where es.js’是:
module.exports.apirouter = require('./api');
module.exports.webrouter = require('./webroutes');因此,目前我正在处理和定义在“/api”中使用api.js前缀的所有路由,而所有其他路由都在“webroutes.js”中定义。
现在,类似地,我需要将前缀'fetch-‘的所有路由定义为单独的js文件’with ch.js‘,因此http://localhost/fetch-one和http://localhost/fetch-two需要在fetch.js中定义。
但是,下面的代码不适用于/fetch-1:
const routes = require('./server/routes');
app.use('/api', routes.apirouter);
app.use('/', routes.webrouter);
app.use('/fetch-*', routes.fetchrouter);routes.js:
module.exports.apirouter = require('./api');
module.exports.webrouter = require('./webroutes');
module.exports.fetchrouter = require('./fetch');fetch.js:在fetch.js中分别为/fetch和/fetch-2定义的路由
var fetchRouter = require('express').Router();
fetchRouter.get('/fetch-one', function(req, res, next) {
// localhost/fetch-one not passed control here
});
fetchRouter.get('/fetch-two', function(req, res, next) {
// localhost/fetch-two not passed control here
})
module.exports = fetchRouter;发布于 2019-11-13 06:58:01
问题是,一旦你这样做了:
app.use('/fetch-*', routes.fetchrouter);然后,路径的/fetch-*部分已经从获取路由器的路由中删除。所以,当你这样做的时候:
fetchRouter.get('/fetch-one', ...)这不匹配,因为/fetch-one已经从路由路径中删除了。该URL必须是/fetch-xxx/fetch-one才能匹配。
最简单的设计是更改路径,以便URL是/fetch/one和/fetch/two,这更符合快递路由器的工作方式。那你就跟:
app.use('/fetch', routes.fetchrouter);还有,在那个路由器里有路由
app.get('/one, ...)
app.get('/two, ...)这是URL设计,它将最干净的路由器与快递路由器最简单的工作方式连在一起。
如果您打算继续使用/fetch-one URL设计,那么另一个想法是让fetchRouter查看所有顶级URL:
app.use('/', fetchRouter);然后,让它只有你想让它看到的顶级路线的路线。如果不处理问题,Express将继续寻找其他匹配的路径:
app.get('/fetch-one', ...);
app.get('/fetch-two', ...);您需要确保没有贪婪的顶级路由器接收所有请求,并确保此路由器只接受它所需的请求,以便其他顶级路由有机会获得匹配。
如果您真的想继续使用路由器的/fetch-*设计,那么您可以进行一些自己的路由和URL比较:
app.use('/fetch-*', routes.fetchrouter);然后,在获取路由器中:
app.get("/", function(req, res, next) {
switch(req.baseUrl) {
case "/fetch-one":
// process /fetch-one here
break;
case "/fetch-two":
// process /fetch-two here
break;
default:
next();
}
});我想到了另一个使用Express参数的选项,您只需要为获取路由而不是路由器使用一个处理程序函数:
app.use('/fetch-:id', routes.fetchHandler);然后,在fetchHandler中:
function fetchHandler(req, res, next) {
switch(req.params.id) {
case "one":
// process /fetch-one here
break;
case "two":
// process /fetch-two here
break;
default:
next();
}
});与大开关不同,您也可以让它由表驱动,如果您有很多路线,它可能会更干净:
app.use('/fetch-:id', routes.fetchHandler);然后,fetchHandler将是一个导出的函数:
const routeTable = {
one: routeOne,
two: routeTwo,
three: routeThree,
....
};
function fetchHandler(req, res, next) {
let fn = routeTable[req.params.id];
if (fn) {
fn(req, res, next);
} else {
next();
}
});
function routeOne(req, res, next) {
...
}
function routeTwo(req, res, next) {
...
}
function routeThree(req, res, next) {
...
}https://stackoverflow.com/questions/58831355
复制相似问题