• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    해결됨

route에서 res.status(201).json시 undefined

23.03.03 02:27 작성 23.03.03 02:33 수정 조회수 342

0

안녕하세요 선생님

게시글 수정을 route에서 처리하고 마지막으로 res.status(201).json(fullPost) 이렇게 게시글 정보를 담아서 보내려는데 자꾸 사가에서 데이터를 undefined로 받습니다..담기 전에 fullPost를 콘솔로 찍어보면 데이터가 잘 들어가 있는데 프론트로 넘어가면 undefined로 바뀌어요.

그래서 단순 문자열도 res.status(201).json('성공');이런 식으로 보내봤는데도data가

이렇게 undefined로 뜨는건 어느 부분을 봐야 하는 건가요?

 

답변 1

답변을 작성해보세요.

0

saga쪽에서 call로 받은 데이터가 제대로 안되어있을 것 같네요. fetcher에서도 return 하셨죠?

뉸뉴님의 프로필

뉸뉴

질문자

2023.03.03

엇..저 게시글 불러올 때 fetcher(SWR 말씀하시는거 맞나요?) 안쓰고 getServerSideProps로 데이터 받아서 수정작업 하고 있었어요. 혹시 수정시에는 SWR을 쓰는게 더 적절한가요?

일단 saga 부분은

function* updatePostAPI(data){
  const postId = data.get('postId');
  return axios.patch(`/post/${postId}/patch`, data);
}

function* updatePost(action){
  try{
      const result = yield call(updatePostAPI, action.data);
      console.log("수정 사가 받은 데이터: ", result.data);
    yield put({
      type: UPDATE_POST_SUCCESS,
      data: result.data
    });
  }
  catch(err){
    console.error(err);
    yield put({
    type: UPDATE_POST_FAILURE,
    error: err.response.data,
  });
  }
}

이렇습니다 선생님

 

보통 불러올 때 swr이 적절하고 수정할때는 saga가 낫죠. result.data가 뭘로 뜨나요? 그게 언디파인드면 서버에서 제대로 안보내주는 겁니다.

뉸뉴님의 프로필

뉸뉴

질문자

2023.03.03

선생님 말씀대로 result.data가 undefined로 뜨고 있어요.

저는 route에서는 잘못된 부분이 안보이는데...

route의 문제 있는 부분 전문은

router.patch('/:postId/patch', isLoggedIn, upload.array('image'), async(req, res, next) => {
  console.log("수정 바디 확인: ", req.body);
  try{
    const postUpdateResult = await Post.update({
      content: req.body.content,
      lookName: req.body.lookName,
      top: req.body.top,
      bottom: req.body.bottom,
      dress: req.body.dress,
      outer: req.body.outer,
      shoes: req.body.shoes,
      acc: req.body.acc   
    }, {
      where: { id: req.body.postId }
    });

    if (postUpdateResult[0] === 0) {
      // 업데이트된 row가 없을 경우 에러 처리
      return res.status(400).send('수정된 내용이 없습니다.');
    }

    const post = await Post.findByPk(req.body.postId);

      const hashtags = [ req.body.top, req.body.bottom, req.body.dress, req.body.outer, req.body.shoes, req.body.acc ];
      
      const newHashtags = hashtags.filter(Boolean);
      console.log("수정 해시태그: " + newHashtags);

      if(req.body.image){
        console.log("게시글 수정 이미지: " + req.body.image);
        await Image.update({src: req.body.image},{where: {PostId: req.body.postId}});
      }

      const set = new Set(newHashtags);

      const finalHashtags = [...set];
       if(finalHashtags !== []){
       const result = await Promise.all(finalHashtags.map((tag) => Hashtag.findOrCreate({
          where: {name: tag.toLowerCase()} 
        })));
        
        await post.setHashtags(result.map((v) => v[0]));
       }

       const fullPost = await Post.findOne({
        where: { id: post.id },
          include: [{
              model: User,
              attributes: ['id', 'nickname']
            },
            {
              model: Image
            }]
        });
      console.log("백에서 보낸 데이터::", fullPost);
    res.status(201).json(fullPost);
  }
  catch(error){
    console.error(error);
    next(error);
  }
});

이런데,

 res.status(201).json(fullPost);

이 부분이 잘못된 거면 router.patch 실행 후 201응답을 안주지 않나요? 일단 요청 보내면 201로 응답이 PATCH /post/14/patch 201 66.511 ms - 532 이렇게 옵니다 선생님ㅠㅠ

updatePostApi 앞에 별이 달려있네요. 얘는 제너레이터가 아닙니다. 지우세요.

그리고 이미 메서드가 patch인데 주소에 /patch를 붙일 필요가없습니다.

뉸뉴님의 프로필

뉸뉴

질문자

2023.03.03

헉;; 네 수정했어요. 아이고 감사합니다 선생님ㅠㅠ 꼼꼼히 살펴보겠습니다....