세상 ㅈ같은 CORS 오류 - 회원가입 부분

Jamkris (승현)·2023년 7월 22일
1

Error

목록 보기
3/3
post-thumbnail

오류

React에서 회원가입 Formik로 작성 후에 axios로 데이터를 보냈는 데


계속 요따구로 뜨는 것이다.

그래서 인터넷에 폭풍 검색을 해보았더니 Proxiy를 설정 해주라고 해서
Client > package.json에
"proxy": "http://localhost:5000",
넣어보아도 똑같았다.

Server > index.js에

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

내 클라이언트 로컬을 연결 해주어도 똑같았다.

혹시 라우터 부분이 문젠가 해서 찾아서
Server > routes > User.js에

router.get('/auth', (req, res) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
})

수정 후

생각보다 많은 것을 짬뽕 시켜야 작동을 하게 된다는 것을 알게 되었다.
먼저 나는 MySQL + Node + React를 사용하고 MySQL은 이미 클라우드타입으로 배포된 서버를 사용하고 있었다.
지금부터 내가 무엇을 추가했는 지 알려주것다.

Server > index.js 여기다

app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true,
    optionsSuccessStatus: 200,
}));

이걸 추가 했다. 여기서 포인트는 Credentials이다. 그리고 이 코드는 포트 설정 전에 index.js 파일의 상단에 적어야 한다.

여기서부터가 진짜다 이걸 안해줘서 오류가 계속 났던것이다. 이 오류 찾는 다고 삽질 ㅈㄴ했다.

바로 Client가 axios로 보낼 때 이다.

Client에 보내는 부분에

axios
	.post('http://localhost:3001/auth', data, {
    	withCredentials: true
    })

withCredentials: true 가 핵심이다. 보낼때 쿠키 즉, 인증헤더를 가지고 보내야하기 때문에 이 부분때문에 Network오류가 뜬 것이다.

+++++

Server > index.js 여기다

app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true,
    optionsSuccessStatus: 200,
}));

참고로 백엔드에서 처리해주어도 된다.

app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true,
    optionsSuccessStatus: 200,
    withCredentials: true
}));

이건 나중에 알게 되었다.

끄읕

profile
Nothing Change If You Don't Try

3개의 댓글

comment-user-thumbnail
2023년 8월 11일

일해라

답글 달기
comment-user-thumbnail
2023년 8월 23일

좀 올리라고

답글 달기
comment-user-thumbnail
2023년 9월 5일

올려줘 ㅜㅜ

답글 달기