Express CORS error

any1ok·2021년 9월 14일
0
post-thumbnail

크롬에서 api 통신을 하니


이런 에러가뜬다

Access to XMLHttpRequest at 'http://localhost:8080/SFSJ_API from origin 'http://localhost:7080' has been blocked by CORS policy: 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.

라는 문제로 에러가 나는 이유는

웹 서버 개발시 자바스크립트로 외부서버의 경로로 ajax요청을 날리면서 실패할 때,

즉 서로 다른 도메인에서 자료를 가져 오면서 CORS(Cross Origin Resource Sharing) 라는 에러가 발생하였다.

CORS는
https://developer.mozilla.org/ko/docs/Web/HTTP/CORS
위링크를 보면 자세하게 알수있고
cors 에러는 간단하게 말하자면 서로다른 도메인끼리 낯을 가려 겁먹고 통신을 끊는거다.(개발자가 만든거 아니랄까바 천성이 아싸인듯하다)

아무튼

npm install --save cors

전 포스팅에도 썼지만 --save 는 무조건 버릇을 들이자

const cors = require('cors');
const corsOptions = {
  origin: "http://localhost:3000",
  credentials: true
}
app.use(cors(corsOptions));

걍 이코드 쓰면 된다 뻘겋게떠서 심각한줄알았는데 쉽다;;

profile
백엔드 개발자

0개의 댓글