inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

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

리액트 쿼리 SSR 부분 질문있습니다.

해결된 질문

403

ㅇㅅㅇ?

작성한 질문수 5

0

강의 프로젝트를 제로초님 깃헙 코드 참고해서

 

리액트 쿼리로 다시 만들어 보는중인데요

 

회원가입 페이지에 SSR 적용하는 과정에서 다음과 같은 에러가 납니다.

 

11.png2.png

 

코드를 보면

//pages/signup.tsx

export const getServerSideProps = async (context: GetServerSidePropsContext) => {
  const cookie = context.req ? context.req.headers.cookie : '';
  axios.defaults.headers.Cookie = '';
  if (context.req && cookie) {
    axios.defaults.headers.Cookie = cookie;
  }
  const response = await loadMyInfoAPI();
  if (response.data) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    };
  }
  return {
    props: {},
  };
};

// api/user.ts

export function loadMyInfoAPI() {
  return axios.get('/user').then((response) => response.data);
}



// routes/user.js

router.get('/', async (req, res, next) => {
  try {
    if (req.user) {
      const fullUwerWithoutPassword = await User.findOne({
        where: { id: req.user.id },
        attributes: { exclude: ['password'] },
        include: [
          { model: Post, attributes: ['id'] },
          { model: User, as: 'Followings', attributes: ['id'] },
          { model: User, as: 'Followers', attributes: ['id'] },
        ],
      });
      res.status(200).json(fullUwerWithoutPassword);
    } else {
      res.status(200).json(null);
    }

 

로그인안한 상태에서 유저 정보를 불러오면 null이 반환되서 에러가

 

나는거 같은데요

 

  const response = await loadMyInfoAPI();
  if (response.data) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    };
  }

 

이부분을 지우고 다음과 같이 바꿔주면

export const getServerSideProps = async (context: GetServerSidePropsContext) => {
  const cookie = context.req ? context.req.headers.cookie : '';
  axios.defaults.headers.Cookie = '';
  if (context.req && cookie) {
    axios.defaults.headers.Cookie = cookie;
  }

  return {
    props: {},
  };
};

 

에러가 사라지는데 지워도 상관없는건가요??

 

 

react redux node.js express next.js

답변 1

0

제로초(조현영)

loadMyInfoApi를 잘못 만드셨을 것 같습니다. return값 확인하세요

0

ㅇㅅㅇ?

loadMyInfoAPI는 제로초님 깃헙 보고 다음과 같이 만들었습니다.

export function loadMyInfoAPI() {
  return axios.get('/user').then((response) => response.data);
}

 

로그인 하지않고 바로 회원가입 페이지로 가니깐 null 값이 반환됩니다.

 

const Signup = () => {
  const router = useRouter();

  const { data: me } = useQuery('user', loadMyInfoAPI);

 

image

router.get('/', async (req, res, next) => {
  try {
    if (req.user) {
      const fullUwerWithoutPassword = await User.findOne({
        where: { id: req.user.id },
        attributes: { exclude: ['password'] },
        include: [
          { model: Post, attributes: ['id'] },
          { model: User, as: 'Followings', attributes: ['id'] },
          { model: User, as: 'Followers', attributes: ['id'] },
        ],
      });
      res.status(200).json(fullUwerWithoutPassword);
    } else {
      res.status(200).json(null);
    }

 

백엔드 쪽은 강의 그대로 만들었습니다.

 

 

0

제로초(조현영)

간단하게 response?.data 하시면 되지 않나요?

0

ㅇㅅㅇ?

주말에 감사합니다 바로 해결되네요

넥스트 버젼 질문

0

78

2

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

0

90

1

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

0

176

1

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

0

103

2

createGlobalStyle의 위치와 영향범위

0

96

2

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

0

92

2

vsc 에서 npm init 설치시 오류

0

148

2

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

0

160

1

화면 새로고침 문의

0

122

1

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

0

154

2

Next 14 사용해도 될까요?

0

452

1

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

0

349

1

url 오류 질문있습니다

0

211

1

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

0

375

1

sudo certbot --nginx 에러

0

1279

2

Minified React error 콘솔에러 (hydrate)

0

470

1

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

0

247

1

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

0

329

1

npm run build 에러

0

519

1

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

0

382

1

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

0

338

2

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

0

289

1

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

0

240

2

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

0

202

1