본문 바로가기
JavaScript/Node.js

Node) 부모 라우터의 req.params를 자식 라우터에게 넘기기 - 중첩라우터

by 박채니 2023. 2. 2.
안녕하세요, 코린이의 코딩 학습기 채니 입니다.
개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.

 

라우터 내에 라우터를 설정할 때, 부모 라우터의 params 값이 넘어오지 않은 경우가 생겼습니다.

(req.params)

 

구조

index.ts (부모라우터)

app.use("/post", postRouter);
app.use("/post/:id/comments", postCommentRouter);

 

postCommentRouter.ts (자식라우터)

router.get("/", getComments);
router.post("/", [body("comment").exists(), body("vote_question_id").exists(), validatorErrorCheck], createComment);
router.post("/:comment_id/like", createOrDeleteCommentLike);
router.delete("/:comment_id", deleteComment);

 

위와 같은 구조를 가질 때 컨트롤러에서 req.params로 부모 라우터에 있는 postId를 가져오려고 하니 undefined가 발생하였습니다.

 

부모 라우터에서 자식 라우터에게 req.params를 넘겨주기 위해선 아래와 같은 설정을 해줘야 합니다.

PickaCommentRouter.ts (자식 라우터)

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

해당 옵션은 부모 라우터의 req.params를 자식에게 넘겨주는 것으로, 만일 부모와 자식 params가 겹치는 경우에는 자식 라우터를 우선으로 합니다.