-
카테고리
-
세부 분야
풀스택
-
해결 여부
해결됨
리액트 쿼리 SSR 부분 질문있습니다.
23.10.08 15:01 작성 조회수 261
0
강의 프로젝트를 제로초님 깃헙 코드 참고해서
리액트 쿼리로 다시 만들어 보는중인데요
회원가입 페이지에 SSR 적용하는 과정에서 다음과 같은 에러가 납니다.
코드를 보면
//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: {},
};
};
에러가 사라지는데 지워도 상관없는건가요??
답변을 작성해보세요.
0
ㅇㅅㅇ?
질문자2023.10.08
loadMyInfoAPI는 제로초님 깃헙 보고 다음과 같이 만들었습니다.
export function loadMyInfoAPI() {
return axios.get('/user').then((response) => response.data);
}
로그인 하지않고 바로 회원가입 페이지로 가니깐 null 값이 반환됩니다.
const Signup = () => {
const router = useRouter();
const { data: me } = useQuery('user', loadMyInfoAPI);
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);
}
백엔드 쪽은 강의 그대로 만들었습니다.
답변 1