SENTENCE U | Day 8 (랜덤 포스트 ID)

블로그 이사 완료·2023년 1월 26일
0
post-thumbnail

포스트 클릭 시 글번호로 찾아 해당 페이지로 이동 기능

글을 누르면 해당 글의 페이지로 이동되는 기능을 추가했다.

일단 글을 누르면 서버로 글의 번호를 보내고

const Post = ({ post, userName, postDate, postId }) => {
  const navigate = useNavigate();

  const onPostHandler = () => {
    axios
      .get(`api/posts/${postId[0]}`, { withCredentials: true })
      .then((res) => {
        console.log(res.data);
        navigate(`/posts/${res.data}`);
      })
      .catch((err) => console.log(err));
  };

  return (
    <PostWrap onClick={onPostHandler}>
      글내용: {post}, 작성자: {userName}, 작성일자: {postDate}
    </PostWrap>
  );
};

몽고디비에서 params의 id와 게시물의 번호가 동일한 글을 가져와서 돌려준다.

 * @path {GET} http://localhost:8000/api/posts
 * @description 특정 게시물 가져오기
 * @returns {post}
 */
router.get('/posts/:id', async (req, res) => {
  try {
    const post = await Post.findOne({ postId: req.params.id });
    if (!post) return res.status(403).json({ loadPost: false });
    return res.status(200).json(post.postId);
  } catch (error) {
    console.log('에러: ', error);
    return res.status(403).json(error.errors);
  }
});


랜덤 글번호 부여 / 작성일자 dayjs로 포맷 사용

새 글을 생성할 때 글 번호를 랜덤으로 생성하고, 생성할 때 dayjs로 연,월,일 포맷으로 저장했다.

router.post('/posts', async (req, res) => {
  try {
    await Post.create({
      // DB에 새 글 생성
      postId: Math.floor(Math.random() * 9 * (Math.random() * 9 * 1000)),
      userId: req.body.userId,
      userName: req.body.userName,
      sentence: req.body.sentence,
      createdDate: now.format('YY년 MM월 DD일'),
      createdAt: Date.now(),
    });
    res.status(200).json({ postSuccess: true });
  } catch (error) {
    console.log('에러: ', error);
    return res.status(403).json(error.errors);
  }
});


profile
https://kyledev.tistory.com/

0개의 댓글