CORS(Cross-Origin Resource Sharing)는 웹 브라우저에서 보안상의 이유로 서로 다른 출처(origin) 간의 리소스 공유를 제어하는 메커니즘이다. 기본적으로, 웹 페이지는 자신이 로드된 출처와 동일한 출처에서만 자원을 요청할 수 있다. 이 제한은 Cross-Origin 요청을 방지하여 악의적인 사이트가 다른 사이트의 데이터를 요청하는 공격을 예방하는 데 도움을 준다.
https://example.com:8080
은 https://example.com
이라는 도메인과 8080
포트를 포함하는 출처를 의미한다.https://example.com
에서 실행 중인 자바스크립트는 다른 출처인 https://another.com
에 직접 요청을 보내지 못한다.Access-Control-Allow-Origin
: 허용된 출처를 지정하는 헤더. 예를 들어, Access-Control-Allow-Origin: *
는 모든 출처를 허용한다.Access-Control-Allow-Methods
: 서버가 허용하는 HTTP 메서드(GET, POST 등)를 지정.Access-Control-Allow-Headers
: 요청 헤더에 포함할 수 있는 헤더를 지정.Access-Control-Allow-Credentials
: 쿠키나 인증 정보 전송을 허용할지 여부를 설정.Authorization
)를 포함하지 않는 요청이다.Access-Control-Allow-Origin
헤더만 설정하여 응답을 보내면 된다.PUT
, DELETE
메서드나 Authorization
헤더를 사용할 때) 브라우저는 먼저 OPTIONS 메서드를 사용하여 서버에 요청을 보낸다.fetch
나 XMLHttpRequest
를 사용하여 서버에 요청을 보낼 때 CORS가 적용된다.javascript
코드 복사
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
credentials: 'same-origin', // 인증 정보 전송 여부
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
javascript
코드 복사
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // 모든 출처 허용
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.get('/data', (req, res) => {
res.json({ message: 'Hello from server!' });
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
CORS는 웹 보안의 중요한 부분으로, 올바르게 설정되지 않으면 원치 않는 보안 취약점이 발생할 수 있다. 따라서 서버와 클라이언트 모두 적절한 CORS 정책을 설정하는 것이 중요하다.