XMLHttpRequest로 Cross Domain Cookie값 읽어오기

Jinseok Lee·2018년 10월 24일
2
post-thumbnail

사연

Next.js + React.js (프론트엔드) 쪽에서 Express.js (백엔드 API서버) 쪽으로 JWT 쿠키값을 요청하는 과정중 Express.js 서버와 Next.js + React.js가 서로 다른 포트(port)위에서 실행되고 있다보니 Cross Domain 에 걸려서 여러가지 셋팅을 해야했다.

1. header값에 Access-Control-Allow-Credentials를 true로 ...

Access-Control-Allow-Origin* 기호가 아닌 도메인(http://localhost:3000)을 명시해 주어야 한다고 한다.

app.all('/*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header('Access-Control-Allow-Methods', 'POST, PUT, GET, DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  res.header('Access-Control-Allow-Credentials', true);
  next();
});

2. XMLHttpRequest 옵션에 credentials 값을 true로

axiox 모듈에는 withCredentials라는 옵션이 있다. 일반 ajaxXMLHttpRequest객체를 사용하면 그에 맞는 옵션 사항 들이 있을것으로 보인다.

export const instanceWithCredential = axios.create({
  baseURL: 'http://localhost:3102/',
  timeout: 180000,
  withCredentials: true
})
...
const url = '/api/v1.0/auth/session';
axiosInstance({
	method: 'get',
	url
}).then(response => {
	// Do Stuff
}).catch(error => {
	// Do Stuff
});
profile
전 위메프, 이직준비중

7개의 댓글

comment-user-thumbnail
2018년 10월 24일

react.js 나 next.js 나 둘다 똑같은 리액트아닌가요?? "Next.js + React.js 사이에서 JWT 쿠키값을 주고받는 과정" 이부분이 이해가안되는데 서버사이드랜더링 시 jwt쿠키값 주고받는 과정이라고 이해하면되나요 ??

1개의 답글
comment-user-thumbnail
2018년 10월 25일

제목에 오타있어요~
CROS -> CORS ? 아니면 Cross?

1개의 답글
comment-user-thumbnail
2018년 10월 29일

Another Typo!!!

axiox 모듈에는 withCredentials라는 옵션이 있다. 

should be axios?

1개의 답글