혼자 적어보는 노트

[Node.js] 로그인 이후 서버 요청 시 에러 발생 해결 본문

NodeJS

[Node.js] 로그인 이후 서버 요청 시 에러 발생 해결

jinist 2022. 4. 10. 05:58

로그인을 한 후 포스트를 게시하려고 하는데 401 에러가 발생했다.

 

401 에러는 로그인 한 유저인지 확인하기 위해 작성을 해놓았던 부분이다.

exports.isLoggedIn = (req, res, next) => {
  if (req.isAuthenticated()) {
    next();
  } else {
    res.status(401).send("로그인이 필요합니다.");
  }
};

post 업로드 요청을 보냈을 때 서버의 middleware에 위와 같이 로그인을 감지하도록 했고
로그인한 상태가 아닐 경우 401코드로 응답하게 했다.

 

하지만 로그인을 한 상태임에도 불구하고
포스트를 작성하면 오류가 생긴다.

 

 

왜일까?

로그인 이후 서버에 요청을 보낼 때 쿠키값을 함께 전달하여 서버에서 로그인 한 유저를 알 수 있는데
도메인이 다르면 (포트번호) 쿠키 또한 전달이 안된다!
== 즉, 누가 요청을 보냈는 지 알 수가 없다.

 

header의 access-control-allow-origin을 통해

해당 도메인의 접근을 허용해 준 것 처럼 (middleware로 cors설정)
쿠키도 허용을 해 주어야 한다.

 

 

🍪 쿠키 허용하는 법

1. node.js(백엔드서버)에 cors설정을 해놓은 부분에 credentials: true를 적어준다.

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

access-controll-allow-credential을 true로 설정할 수 있다. (default값은 false)

 

2. 요청을 보내는 프론트엔드에서 withCredentials: true를 함께 전달해준다.

function addPostAPI(data) {
  return axios.post("/post", { content: data }, { withCredentials: true });
}

 

요청을 보내는 브라우저와 응답하는 서버 양 쪽 모두 credentials를 넣어주어야 쿠키가 전달된다.

 


✅ 참고로 axios에서는 saga들을 관리하는 index.js에서
아래와 같은 설정으로 모든 axios 요청에 대해 withCredentials를 설정할 수 있다.

axios.defaults.withCredentials = true;

❗❗ withCredentials와 credentials 설정을 true로 변경하고 로그인 시

아래와 같은 에러를 만날 수 있다.

 

Access to XMLHttpRequest at 'http://localhost:8080/user/login' from origin 'http://localhost:3060' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

 

 

crednetial을 true로 설정하게 될 경우
서버에서 cors설정의 origin에 특정 도메인을 넣어주지 않고

wildcard인 "*"를 넣는다면 에러가 생긴다.
==> origin 허용 주소만 변경하면 해결 가능하다.
origin : true를 해도 해결이 되지만 보안부분에서 문제가 될 수 있다.

Comments