pre-프로젝트 5일차/stackoverflow 클론

Kyoorim LEE·2022년 9월 1일
1

프로젝트 진행사항

공통

백엔드

CORS 에러 해결 => cors 필터 or 어노테이션???

프론트엔드

글 작성/조회/삭제/수정 기능 구현

해야할 일

글 작성 기능 구현

TIL

cors 에러

오늘은 하루종일 cors에러와의 싸움을 했다..

1. 게시글 등록 구현 중 cors 에러 발생

우선 axios로 게시글 POST 처리해주었다.

async function submitHandler(event) {
    event.preventDefault();

    try {
      const question = {
        title: titleRef.current.value,
        content: contentRef.current.value,
      };

      const enteredTitleIsValid = question.title.trim() !== '';
      const enteredContentIsValid = question.content.trim() !== '';

      let formIsValid = false;
      if (enteredTitleIsValid && enteredContentIsValid) {
        formIsValid = true;
      }
      if (!formIsValid) {
        return;
      }
      // eslint-disable-next-line
      console.log(question);

      const response = await axios.post('/v1/posts', question);
      // eslint-disable-next-line
      console.log(response.data);
    } catch {
      // eslint-disable-next-line
      console.log('Error occured');
    }
  }

그리고 console을 보니 CORS에러가 났다는 에러창이 떠있었다

2. package.json에 프록시 추가하여 해결 시도

https://sundries-in-myidea.tistory.com/71
팀원 분이 보내주신 글에 package.json에 프록시 주소를 추가하여 간단하게 해결할 수 있다는 문구가 있어 추가하고 다시 시도해보았지만..

여전히 같은 에러가 발생했다

3. 남이 만든 프록시 서버를 이용하는 방법

폭풍 검색을 하던 와중 흥미로운 블로그 발견!
https://xiubindev.tistory.com/115

대충 요약하면 클라이언트에서 외부 서버로 바로 요청하는 것이 아니라 프록시 서버를 사용하여 우회한다는 것
브라우저와 서버 간의 통신을 도와주는 중계서버 역할을 한다고 한다

방법은 간단하다. 엔드포인트 앞에 서버 주소를 추가로 써주면 된다.

추가할 서버주소: https://cors-anywhere.herokuapp.com/

 const response = await axios.post('https://cors-anywhere.herokuapp.com/http://localhost:8080/v1/posts', question);
      // eslint-disable-next-line
      console.log(response.data);
    } catch {
      // eslint-disable-next-line
      console.log('Error occured');
    }

그런 다음 실행시켜보니.. cors 에러는 없어졌지만 데이터 load가 안된단다 🤯

어차피 임시방편이기에.. 깔끔하게 이 방법은 포기하기로 했다.

4. 엔드포인트 작성방법

그러던 와중... 백엔드 동료 한 분도 폭풍 검색을 하던 와중 코멘트를 주셨다.

바로 axios문의 엔드포인트를 8080 뒤 경로문만 집어넣는 것!

여기까지 한 후 npm install을 다시하고 console창을 봤더니.. ta da..

감동적인 콘솔창의 모습이다.

여기서 진짜 다시 한 번 중요한거!!!!
package.json 내용 변경 후에는 반드시 npm install을 다시 해서 변경된 내용을 최종적으로 반영해줘야한다! npm install까지 해야 package.json의 내역대로 node_modules에 깔리는 것이기 때문.... 단순히 바꾸고 저장만 해서는 안된다
(이거 몰라서 진짜 한 세시간은 헤맸다..)

어찌보면 기본적인 내용일 수도 있겠지만,
저걸 몰라 족히 3-4시간은 헤맸던 나를 보고
기본의 중요성을 다시 한 번 느끼게 되었다 하핳

profile
oneThing

0개의 댓글