본문 바로가기

React

[Error] TypeError: Cannot read properties of undefined (reading 'id')

TypeError: Cannot read properties of undefined (reading 'id') 에러가 발생했다

 

로그인을 하면 정보를 받아서 id값을 읽어 와야 하는데 읽지 못하니

게시글 등록, 로그아웃도 안 된다

 

알고 보니 코드 하나가 빠져 있었다........

 

 

 

 


서버 index.js에 cors 설정

 

app.use(
  cors({
    origin: "http://localhost:3000",
    credentials: true, 
);

credentials: true 로 쿠키를 보내는 코드이다

이걸 쓰려면 클라이언트 쪽에서도 받을 수 있는 코드를 적어줘야 한다

 

 

 


 

클라이언트 saga/index.js

import { all, fork } from "redux-saga/effects";
import axios from "axios";
import postSaga from "./post";
import userSaga from "./user";

axios.defaults.baseURL = "http://localhost:3075";
axios.defaults.withCredentials = true;

export default function* rootSaga() {
  yield all([fork(postSaga), fork(userSaga)]);
}

이런 식으로 axios로 api 요청을 보낼 때 axios.defaults.withCredentials = true; 로 해줘야 쿠키를 받을 수 있다

 

저 한 줄 빼먹어서 계속 id를 찾을 수 없다고 나왔다.......

 

 

 


function logInAPI(data) {
  return axios.post("/user/login", data, { withCredentials: true });
}

이렇게 api 함수에 하나만 넣어줘도 된다

default로 하는 게 더 편하긴 하지만...