inflearn logo
강의

Khóa học

Chia sẻ kiến thức

[Renewal] Tạo NodeBird SNS bằng React

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

Đã giải quyết

485

bbibibbibi224677

23 câu hỏi đã được viết

0

안녕하세요 선생님

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

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

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

 

redux react nodejs express Next.js

Câu trả lời 1

0

zerocho

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

0

bbibibbibi224677

엇..저 게시글 불러올 때 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,
  });
  }
}

이렇습니다 선생님

 

0

zerocho

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

0

bbibibbibi224677

선생님 말씀대로 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 이렇게 옵니다 선생님ㅠㅠ

0

zerocho

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

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

0

bbibibbibi224677

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

넥스트 버젼 질문

0

77

2

로그인시 401 Unauthorized 오류가 뜹니다

0

88

1

무한 스크롤 중 스크롤 튐 현상

0

174

1

특정 페이지 접근을 막고 싶을 때

0

103

2

createGlobalStyle의 위치와 영향범위

0

95

2

인라인 스타일 리렌더링 관련

0

90

2

vsc 에서 npm init 설치시 오류

0

146

2

nextjs 15버전 사용 가능할까요?

0

158

1

화면 새로고침 문의

0

121

1

RTK에서 draft, state 차이가 있나요?

0

153

2

Next 14 사용해도 될까요?

0

452

1

next, node 버전 / 폴더 구조 질문 드립니다.

0

349

1

url 오류 질문있습니다

0

211

1

ssh xxxxx로 우분투에 들어가려니까 port 22: Connection timed out

0

372

1

sudo certbot --nginx 에러

0

1271

2

Minified React error 콘솔에러 (hydrate)

0

469

1

카카오 공유했을 때 이전에 작성했던 글이 나오는 버그

0

246

1

프론트서버 배포 후 EADDRINUSE에러 발생

0

325

1

npm run build 에러

0

518

1

front 서버 npm run build 중에 발생한 에러들

0

381

1

서버 실행하고 브라우저로 들어갔을때 404에러

0

337

2

css 서버사이드 랜더링이 적용되지 않아서 문의 드립니다.

0

286

1

팔로워 3명씩 불러오고 데이터 합쳐주는걸로 바꾸고 서버요청을 무한으로하고있습니다.

0

237

2

해시태그 검색에서 throttle에 관해 질문있습니다.

0

201

1