CORS(Cross-Origin Resource Sharing)는 웹 애플리케이션에서 동일 출처 정책(Same-Origin Policy)을 우회하여 다른 도메인의 리소스에 접근하는 것을 허용하는 정책입니다.
기본적으로 브라우저는 보안상의 이유로 다른 출처의 리소스 요청을 차단합니다.
따라서 서버 측에서 CORS를 활성화하려면 특정 도메인이나 출처에서 온 요청을 허용해야 합니다.
1. Express.js를 사용한 기본 서버에서 CORS 설정
모든 출처에 대한 CORS 허용하기
npm install cors
const express = require('express');
const cors = require('cors');
const app = express();
// 미들웨어로 CORS 활성화
app.use(cors());
// 라우트 정의 및 처리 로직 작성
app.listen(3000, () => {
console.log('서버가 3000번 포트에서 실행 중입니다.');
});
2. 선택적인 출처에 대한 CORS 허용하기
안전하게 설정을 위해 클라이언트가 요청할 수 있는 도메인 지정 필요
const express = require('express');
const cors = require('cors');
const app = express();
// 선택적인 출처에 대해서만 CORS 활성화
const corsOptions = {
origin: 'https://example.com',
};
app.use(cors(corsOptions));
// 라우트 정의 및 처리 로직 작성
app.listen(3000, () => {
console.log('서버가 3000번 포트에서 실행 중입니다.');
});
3. 고급 옵션 적용
* methods: 서버가 허용하는 HTTP 메서드 목록. 기본적으로 GET, POST, HEAD 메서드가 자동으로 포함
* allowedHeaders: 서버가 허용하는 요청 헤더 목록.
* exposedHeaders: 서버에서 클라이언트로 반환되는 응답 중 노출시키고자하는 응답 헤더 목록.
* credentials: 자격증명(Credentials) 사용 여부.
* maxAge: 요청의 유효 기간 설정.
const express = require('express');
const cors = require('cors');
const app = express();
// 고급 CORS 옵션 설정
const corsOptions = {
origin: 'https://example.com', // 허용할 출처
methods: ['GET', 'POST'], // 허용할 HTTP 메서드
allowedHeaders: ['Content-Type', 'Authorization'], // 허용할 요청 헤더
exposedHeaders: ['Content-Length', 'Authorization'], // 노출할 응답 헤더
credentials: true, // 자격증명(Credentials) 사용 여부 (쿠키 전송 등)
maxAge: 3600, // 프리플라이트(OPTIONS) 요청의 유효 기간 (초 단위)
};
app.use(cors(corsOptions));
// 라우트 정의 및 처리 로직 작성
app.listen(3000, () => {
console.log('서버가 3000번 포트에서 실행 중입니다.');
});
* 여러 개의 도메인을 배열로 지정 가능
const corsOptions = {
origin: ['https://example.com', 'https://another-domain.com'],
};
4. 커스텀 로직 적용
origin 옵션에 함수를 전달하여 도메인 확인 로직을 직접 구현 가능
const express = require('express');
const cors = require('cors');
const app = express();
// 커스텀 CORS 로직 적용
const corsOptions = {
origin: (origin, callback) => {
if (origin === 'https://example.com') {
callback(null, true);
} else {
callback(new Error('CORS not allowed'));
}
},
};
app.use(cors(corsOptions));
// 라우트 정의 및 처리 로직 작성
app.listen(3000, () => {
console.log('서버가 3000번 포트에서 실행 중입니다.');
});
반응형
'개발정리 (nodeJS)' 카테고리의 다른 글
[nodeJS] JWT 인증하기 (0) | 2023.08.31 |
---|---|
[nodeJS] Node.JS 서버의 사용량 제한 구현하기 (0) | 2023.08.30 |
[nodeJS] Node.JS와 mongoDB 연동 방법 (0) | 2023.08.08 |
[nodeJS] Node.JS와 mySQL 연동 방법 (0) | 2023.08.07 |
[nodeJS] 에러 및 예외 처리 방법 (0) | 2023.08.06 |