강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

hib4888님의 프로필 이미지
hib4888

작성한 질문수

[리뉴얼] React로 NodeBird SNS 만들기

쿼리스트링과 lastId 방식

GET http://localhost:3065/undefined 404 (Not Found) 에러질문입니다.

작성

·

935

0

홈페이지를 접속할때만 다음과 같은 클라이언트 에러가 발생해서 질문드립니다.

Recipe.io - Chrome 2022-09-27 오후 9_16_15 (2).pngRecipe.io - Chrome 2022-09-27 오후 9_18_05 (2).pngRecipe.io - Chrome 2022-09-27 오후 9_16_03 (2).pngRecipe.io - Chrome 2022-09-27 오후 9_16_09 (2).pngRecipe.io - Chrome 2022-09-27 오후 9_30_58 (2).pngindex.js - prepare - Visual Studio Code [Administrator] 2022-09-27 오후 9_16_25 (2).png이미지를 참조하는 부분에서 에러가 발생하는 것 같아서 이미지를 참조하는 다른 페이지를 확인해봤는데 홈페이지에서만 해당 에러가 발생하고 있습니다.

모든 action은 정상적으로 동작하며 서버쪽의 이미지도 정상적으로 저장되어 있습니다.

혹시 어떤 부분에서 문제가 발생한건지 힌트를 조금 주시면 감사하겠습니다.

 

postcard

 cover={
          <CardImageWrapper>
            <ImageWrapper alt="post image" src={`http://localhost:3065/${post.Images[0]?.src}`} onClick={showPostModal} />      
          </CardImageWrapper>
        }

 

reducer

      case LOAD_POSTS_REQUEST:
        draft.loadPostsLoading = true;
        draft.loadPostsDone = false;
        draft.loadPostsError = null;
        break;
      case LOAD_POSTS_SUCCESS:
        draft.loadPostsLoading = false;
        draft.loadPostsDone = true;
        draft.firstPageLoad = false;
        draft.mainPosts = draft.mainPosts.concat(action.data);
        draft.hasMorePosts = action.data.length === 10;
        break;
      case LOAD_POSTS_FAILURE:
        draft.loadPostsLoading = false;
        draft.loadPostsError = action.error;
        break;      

 

saga

function loadPostsAPI(lastId) {    
  return axios.get(`/posts?lastId=${lastId || 0}`);
}

function* loadPosts(action) {   
  try {        
    const result = yield call(loadPostsAPI, action.lastId); 
    yield put({
      type: LOAD_POSTS_SUCCESS,
      data: result.data,
    })
  } catch(err) {
    yield put({ 
      type: LOAD_POSTS_FAILURE,
      error: err.response.data 
    })
  }  
}

 

router

router.get('/', async (req, res, next) => { // loadPostsAPI / GET /posts
  try {
    const where = {};
    if (parseInt(req.query.lastId, 10)) {
      where.id = { [Op.lt]: parseInt(req.query.lastId, 10) };
    }

    const posts = await Post.findAll({
      where,
      limit: 10,
      order: [
        ['createdAt', 'DESC'],
        [Comment, 'createdAt', 'DESC'],
      ],
      include: [{
        model: User,
        attributes: ['id', 'nickname'],
      }, {
        model: Image,
      }, {
        model: Comment,
        include: [{
          model: User,
          attributes: ['id', 'nickname'],
        }],
      }, {
        model: User,
        as: 'Likers',
        attributes: ['id'],
      }],
    });
    console.log(posts);
    res.status(200).json(posts);
  } catch (error) {
    console.error(error);
    next(error);
  }
});

답변 1

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

이미지가 없는 게시글이 있는 건 아닌가요? 애초에 이미지가 없으면 CardImageWrapper를 렌더링할 필요가 없을 것 같습니다.

hib4888님의 프로필 이미지
hib4888
질문자

감사합니다!! 말씀대로 이미지가 없는 게시글때문에 해당 오류가 발생했었네요 덕분에 잘 해결됬습니다.

그리고 해당 강의와는 관련없는 질문이긴한데 혹시 라우터에서 매핑테이블에 컬럼에 접근하는 방법은 없을까요?

마이페이지에 접근할 때 좋아요한 게시글을 가져오는 기능을 만들고 있습니다.

그래서 다음과 같이 where조건절에 Like테이블의 PostId를 사용하고 싶은데

혹시 방법이 있을까요?

router.get('/liked', isLoggedIn, async (req, res, next) => { // loadLikePostAPI / GET /user/liked
  try {
    const likedPost = await Post.findAll({      
      where: { [Op.and]: [
        { UserId: req.user.id }, 
        { id: 매핑테이블 PostId컬럼 }] // 매핑테이블의 컬럼 접근 방법(?)
      },      
      order: [[ 'createdAt', 'DESC' ]],      
      include: [{
        model: User,        
        attributes: ['id', 'nickname'],
      }, {
        model: User,
        as: 'Likers',
        attributes: ['id'],
      }, {
        model: Comment,
        include: [{
          model: User,
          attributes: ['id', 'nickname'],
        }],
      }, {
        model: Image,
      }]
    });
    res.status(200).json(likedPost);
  } catch (error) {
    console.error(error);
    next(error);
  }
});

 

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

해당 테이블에 대한 include 에서 where 넣으시면 됩니다. include: User, as: 'Likers', where: ...

hib4888님의 프로필 이미지
hib4888

작성한 질문수

질문하기