[express.js] CORS

김민재·2024년 4월 2일

express.js

목록 보기
18/39

CORS(Cross Origin Resource Sharing)란?

  • 도메인 및 포트가 다른 서버로 클라이언트가 요청했을 때 브라우저가 보안상의 이유로 API를 차단하는 문제이다. 로컬 서버에서 다른 서버로 호출할 때 발생한다.

    해결방법

    • npm i cors
      미들웨어 cors를 활용한다.
    • 설치 후에 서버를 실행할 파일에
      const cors = require('cors');
      app.use(cors());
    • 특정 URL만 허용하고 싶다면
      const cors = require('cors');
      const corsOptions = {
       origin: "http://localhost:3000",
       credentials: true,
         }
         
        app.use(cors(corsOptions));
  • 이런 식으로 cors 미들웨어를 이용해서 해결할 수가 있다.

profile
개발 경험치 쌓는 곳

0개의 댓글