NodeJS 快速使用路由器,路径中有段塞

ykejflvf  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(161)

我构建了一个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);
有谁知道我该怎么做吗?多谢了!

i1icjdpr

i1icjdpr1#

分别声明产品和类别路由:

const express = require('express');

const productsRouter = express.Router();

productsRouter.get('/', (req, res) => {
    res.send('[GET] - Products root!');
});

productsRouter
    .route('/:productId/category')
    .get((req, res) => {
        res.send('[GET] - categoryRouter root!');
    })
    .post((req, res) => {
        res.send('[POST] - categoryRouter root!');
    });

module.exports = productsRouter;

字符串
并将它们与以下各项一起使用:

const express = require('express');
const productsRouter = require('./products-router');

const app = express();
const port = 3000;

app.use('/api/products', productsRouter);

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

相关问题