我构建了一个categoryRouter
,它有几个路由。我想在另一个路由器中使用该路由器,但也要指定一个slug,如下所示:parentRouter.use('/:slug/categories', categoryRouter)
个categoryRouter
路由中的req.params
对象似乎是空的。
示例代码:
In "index.js" file:
const express = require('express');
const productsRouter = require('./products-router');
const app = express();
const port = 3000;
const apiRouter = express.Router();
apiRouter.use('/products', productsRouter);
app.use('/api', apiRouter);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
字符串
In "products-router.js" file:
const express = require('express');
const categoryRouter = require('./category-router');
const productsRouter = express.Router();
productsRouter.get('/', (req, res) => {
res.send('[GET] - Products root!');
});
productsRouter.use('/:productId/category', categoryRouter);
module.exports = productsRouter;
型
In "category-router.js" file:
const express = require('express');
const categoryRouter = express.Router();
categoryRouter.get('/', (req, res) => {
console.log(req.params); // outputs {}
res.send('[GET] - categoryRouter root!');
});
categoryRouter.post('/', (req, res) => {
console.log(req.params); // outputs {}
res.send('[POST] - categoryRouter root!');
});
module.exports = categoryRouter;
型
当我在categoryRouter
路由中指定整个路径时,如下所示:
categoryRouter.get('`/:productId/category`', (req, res) => {
console.log(req.params);
res.send('[GET] - categoryRouter root!');
});
型
同时更改productsRouter
内部的路径:productsRouter.use('/', categoryRouter);
有谁知道我该怎么做吗?多谢了!
1条答案
按热度按时间i1icjdpr1#
分别声明产品和类别路由:
字符串
并将它们与以下各项一起使用:
型