NodeJS 如何从Express.js中的嵌套路由读取参数

oxf4rvwz  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(149)

我的路由定义如下:

export const router = Router();

const appRoutes = [
  {
    path: "/",
    router: usersRouter,
  },
  {
    path: "/games/",
    router: gamesRouter,
  },
  {
    path: "/games/:gameId/pieces/",
    router: piecesRouter
  }
];

appRoutes.forEach((route) => router.use(route.path, route.router));

当我发送一个请求到例如“/games/4/pieces/”时,控制器的正确操作正在被拾取,当我记录req对象时,我可以看到gameId在那里:

baseUrl: '/games/4/pieces',
originalUrl: '/games/4/pieces',
_parsedUrl: Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: null,
  query: null,
  pathname: '/',
  path: '/',
  href: '/',
  _raw: '/'
},
params: {},
query: {},

然而,它不在参数中,当我读取req.params时,它只是一个空哈希。就好像Express.js只读取嵌套路由器本身中列出的参数,看起来像这样:

import { Router } from "express";
import { index } from "../controllers/pieces.controller";

export const piecesRouter = Router();

piecesRouter.get("/", index);

传递给get方法的路径没有任何变量,所以我在参数中没有得到任何变量。我如何访问这些参数?

xbp102n0

xbp102n01#

您应该将{ mergeParams: true }选项传递给express.Router()
保留父路由器的req.params值。如果父级和子级的参数名冲突,则优先使用子级的值。
该选项适用于express 4.5.0+。默认值为false
例如

import express, { Router } from 'express';

const app = express();

const router = Router();
const piecesRouter = Router({ mergeParams: true });

piecesRouter.get('/', (req, res) => {
  console.log(req.params);
  res.sendStatus(200)
})

router.use('/games/:gameId/pieces/', piecesRouter)

app.use(router);

app.listen(3000, () => console.log('Server is listening on http://localhost:3000'))

http://localhost:3000/games/4/pieces端点发送GET HTTP请求,服务器记录:

Server is listening on http://localhost:3000
{ gameId: '4' }

相关问题