강의

멘토링

로드맵

Inflearn brand logo image

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

ㅇㅅㅇ?님의 프로필 이미지
ㅇㅅㅇ?

작성한 질문수

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

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

해결된 질문

작성

·

377

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: {},
  };
};

 

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

 

 

답변 1

0

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

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

ㅇㅅㅇ?님의 프로필 이미지
ㅇㅅㅇ?
질문자

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);
    }

 

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

 

 

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

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

ㅇㅅㅇ?님의 프로필 이미지
ㅇㅅㅇ?
질문자

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

ㅇㅅㅇ?님의 프로필 이미지
ㅇㅅㅇ?

작성한 질문수

질문하기