[exress.js] router 경로에 있는 req.params.id 가져오기

김민재·2024년 4월 16일

express.js

목록 보기
34/39

app.js에 router 경로를 설정 해줬는데 route 파일에서는 req.params.id를 가져올 수 없다. 이때 mergeParams: true로 설정해주면 된다.

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

app.use("/posts/:id/comments", commentsRouter);

router.post('/', checkAuthenticated, async (req, res) => {
    // app.js에서 router 경로를 정의 해줬기 때문에 여기서는 할 필요가 없다.
    // 그런데 post를 찾으려면 req.params.id를 가져와야 하는데 app.js router 경로에 있기 때문에
    // 여기서는 사용이 불가능하다. 그때  const router = express.Router({mergeParams: true}); 설정 해주면 된다.
    const post = await Post.findById(req.params.id);

    let text = req.body.text
    if (post) {
         Comment.create({
            text,
            author: {
              id: req.user._id,
              username: req.user.username
            }
         }).then((comment) => {
             console.log(comment)
             post.comments.push(comment)
             post.save()

             req.flash('success', '댓글이 생성되었습니다.')
             res.redirect('/posts')
         }).catch((error) => {
            console.log(error)
            req.flash('error', '댓글 생성이 실패했습니다.')
            res.redirect('/posts')
            })
    } else {
        req.flash('error', '포스트가 존재하지 않습니다.')
        res.redirect('/posts')
    }
})
profile
개발 경험치 쌓는 곳

0개의 댓글