cookie가 있는걸로 봐서는 프론트에서 인식을 못하고 있는것 같다고 하셔서 살펴보는데 찾지를 못하겠습니다..
일단 pages/index,js의 getServerSideProps 는 문제가 없어 보입니다.
```javascript
export const getServerSideProps = wrapper.getServerSideProps((store) => async ({ req }) => {
const cookie = req ? req.headers.cookie : ''; // req가 있다면 cookie에 요청에 담겨진 cookie를 할당한다.
axios.defaults.headers.Cookie = ''; // 요청이 들어올 때마다 초기화 시켜주는 것이다. 여기는 클라이언트 서버에서 실행되므로 이전 요청이 남아있을 수 있기 때문이다
if (req && cookie) {
axios.defaults.headers.Cookie = cookie; // 서버일때랑 cookie를 써서 요청을 보낼 때만 headers에 cookie를 넣어준다
}
store.dispatch({
type: LOAD_MY_INFO_REQUEST, // user
});
store.dispatch({
type: LOAD_POSTS_REQUEST, // post
});
store.dispatch(END);
await store.sagaTask.toPromise(); // store/configureStore.js > store.sagaTask
}); // 이 부분이 Home 보다 먼저 실행됨
```
그리고 reducer 또한 문제가 없어 보입니다.
case LOAD_MY_INFO_REQUEST:
draft.loadMyInfoLoading = true;
draft.loadMyInfoDone = false;
draft.loadMyInfoError = null;
break;
case LOAD_MY_INFO_SUCCESS:
draft.loadMyInfoLoading = false;
draft.me = action.data;
draft.loadMyInfoDone = true;
break;
case LOAD_MY_INFO_FAILURE:
draft.loadMyInfoLoading = false;
draft.loadMyInfoError = action.error;
break;
이어서 saga user 입니다.
function loadMyInfoAPI() {
return axios.get('/user'); // GET(Browser)
}
function* loadMyInfo() {
try {
const result = yield call(loadMyInfoAPI);
console.log(result);
yield put({
type: LOAD_MY_INFO_SUCCESS,
data: result.data,
});
} catch (err) {
console.error(err);
yield put({
type: LOAD_MY_INFO_FAILURE,
error: err.response.data,
});
}
}
routes/user 입니다.
router.get('/:userId', async (req, res, next) => {
try {
const fullUserWithoutPassword = await User.findOne({
where: { id: req.params.userId },
attributes: {
exclude: ['password'], // 원하는 정보만 가져오거나 가져오지 않겠다 / 현재: pw 빼고 다 가져오겠다
},
include: [
{
model: Post,
attributes: ['id'],
},
{
model: User,
as: 'Followers',
attributes: ['id'],
},
{
model: User,
as: 'Followings',
attributes: ['id'],
},
], // 가져올 정보중 뺄 것들
});
if (fullUserWithoutPassword) {
const data = fullUserWithoutPassword.toJSON();
data.Posts = data.Posts.length; // 개인정보 침해 예방
data.Followers = data.Followers.length;
data.Followings = data.Followings.length;
res.status(200).json(data);
} else {
res.status(404).send('존재하지 않는 사용자입니다.');
}
} catch (err) {
console.error(err);
next(err);
}
});
추가로 middleware 입니다.
exports.isLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
next(); // 비어있으면 다음 미들웨어로 간다
} else {
res.status(401).send('로그인이 필요합니다.');
}
};
exports.isNotLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
next(); // 비어있으면 다음 미들웨어로 간다
} else {
res.status(401).send('로그인하지 않은 사용자만 접근이 가능합니다.');
}
};
살펴본 결과 로직은 문제가 없어보이는데 혹시 front에서
getServerSideProps 문법이 강의와 다른데 라이브러리 사이트를 보고 적용했던겁니다. 제가 너무 헤매고 있어서 보시고 조언 주신다면 감사하겠습니다...
network 401
답변 9