TIL&WIL/TIL

params [ TIL ] [ node.js ]

muyeon 2023. 6. 24. 16:07

 

Problem

 

req.params 가 빈 객체가 전달된다.

// index.js

const express = require("express");
const commentRouter = require("./comments");
const postRouter = require("./posts");
const router = express.Router();

router.use("/posts", postRouter);
router.use("/posts/:_postId", commentRouter)


module.exports = router;
// comments.js
router.post("/comments", async (req, res) => {
  try {
    const postId = req.params;
    const { user, password, content } = req.body;

    if (!content) {
      return res.status(400).json({ message: "댓글 내용을 입력해주세요." });
    }

    const comment = await Comment.create({
      postId: postId["_postId"],
      user,
      password,
      content,
    });

    return res.json({ message: "댓글을 생성하였습니다." });
  } catch (err) {
    return res
      .status(400)
      .json({ message: "데이터 형식이 올바르지 않습니다." });
  }
});

Try

 

쿼리로 받아보려고도 시도해보았고, 라우터 명을 전부 단축시켜서 바꿔볼려고 했으나 그건좀 너무 아닌것 같아서 포기

다른분들께도 많이 물어봤으나 원하는 답을 얻지는 못했었다.

 


Solve

 

// index.js
const express = require("express");
const commentRouter = require("./comments");
const postRouter = require("./posts");
const router = express.Router();

router.use("/posts", postRouter, commentRouter); // 게시글 댓글

module.exports = router;
// comments.js
// 댓글 생성
router.post("/:_postId/comments", async (req, res) => {
  try {
    const postId = req.params;
    const { user, password, content } = req.body;

    if (!content) {
      return res.status(400).json({ message: "댓글 내용을 입력해주세요." });
    }

    const comment = await Comment.create({
      postId: postId["_postId"],
      user,
      password,
      content,
    });

    return res.json({ message: "댓글을 생성하였습니다." });
  } catch (err) {
    return res
      .status(400)
      .json({ message: "데이터 형식이 올바르지 않습니다." });
  }
});

What I Learned

사실 간단한 문제였다. 함수에서 인자를 가져오는 느낌인데 현재 함수에서 다른 함수의 인자를 가져오려는 행동과 같았다.

그래서 코드를 수정했고 동적URL 에 사용에대한 지식을 얻을 수 있었다.