

동일 출처 정책 = ‘같은 출처의 리소스만 공유가 가능하다’는 정책
여기서 '출처(Origin)'는 프로토콜, 호스트, 포트의 조합으로 하나라도 다르면 동일한 출처로 아니게 됨.
http://codestates.com:81 vs http://codestates.comhttps://codestates.com:443 vs https://codestates.com잠재적으로 해로울 수 있는 문서를 분리함으로써 공격받을 수 있는 경로를 줄여줌
But, 실제 개발에서는 모두 다른 출처의 리소스를 사용하게 되기 때문에 이를 해결해줄 CORS가 필요함.
교차 출처 리소스 공유 = 추가 HTTP 헤더를 사용해 한 출처에서 실행 중인 웹 애플리케이션이 다른 출처의 선택한 자원에 접근할 수 있는 권한을 부여하도록 브라우저에 알려주는 체제 (MDN 정의)

이 에러를 다시 해석해보면
다른 출처의 리소스를 가져오려고 했지만 SOP 때문에 접근이 불가능합니다.
CORS 설정을 통해 서버의 응답 헤더에 ‘Access-Control-Allow-Origin’을 작성하면 접근 권한을 얻을 수 있습니다.
⇒ 즉, CORS는 오히려 위의 에러를 해결해줄 수 있는 방안!!
실제 요청을 보내기 전, OPTIONS 메서드로 사전 요청을 보내 해당 출처 리소스에 접근 권한이 있는지부터 확인하는 것

위의 그림과 같이 브라우저는 서버에 실제 요청을 보내기 전, 프리플라이트 요청을 보내고, 응답 헤더의 Access-Control-Allow-Origin으로 요청을 보낸 출처가 돌아오면 실제 요청을 보내게 됨.

만약에 요청을 보낸 출처가 접근 권한이 없다면, 브라우저에서 CORS 에러를 띄우게 되고, 실제 요청은 전달 X


GET, HEAD, POST 요청 중 하나Accept, Accept-Language, Content-Language, Content-Type 헤더의 값만 수동으로 설정가능Content-Type 헤더에는 application/x-www-form-urlencoded, multipart/form-data, text/plain 값만 허용프론트 측: 요청 헤더에 withCredentials : true 를 넣어줘야 함.
서버 측: 응답 헤더에 Access-Control-Allow-Credentials : true 를 넣어줘야 함.
서버 측: Access-Control-Allow-Origin 을 설정할 때, 모든 출처를 허용한다는 뜻의 와일드카드(*)로 설정하면 에러가 발생. 인증 정보를 다루는 만큼 출처를 정확하게 설정해야 함.
const http = require('http');
const server = http.createServer((request, response) => {
// 모든 도메인
response.setHeader("Access-Control-Allow-Origin", "*");
// 특정 도메인
response.setHeader("Access-Control-Allow-Origin", "https://codestates.com");
// 인증 정보를 포함한 요청을 받을 경우
response.setHeader("Access-Control-Allow-Credentials", "true");
})
const cors = require("cors");
const app = express();
//모든 도메인
app.use(cors());
//특정 도메인
const options = {
origin: "https://codestates.com", // 접근 권한을 부여하는 도메인
credentials: true, // 응답 헤더에 Access-Control-Allow-Credentials 추가
optionsSuccessStatus: 200, // 응답 상태 200으로 설정
};
app.use(cors(options));
//특정 요청
app.get("/example/:id", cors(), function (req, res, next) {
res.json({ msg: "example" });
});
⇒ Node.js 뿐만 아니라 Express, Fastify 등 다른 서버 환경에서도 CORS 설정가능
HTTP 트랜잭션 해부(Anatomy of an HTTP Transaction)
참고해서 문제 품.
const http = require('http');
const PORT = 4999;
const ip = 'localhost';
const server = http.createServer((request, response) => {
// 메소드가 options이면 CORS 설정을 돌려줘야 한다
if (request.method === 'OPTIONS') {
response.writeHead(200, defaultCorsHeader)
response.end('hello mini-server sprints')
}
// 메소드가 POST고, url이 /upper면 대문자로 응답을 돌려줘야 한다
if(request.method === 'POST' && request.url === '/upper') {
let body = ''; //여기 다시함
request.on('data', (chunk) => {
body = body + chunk;
})
request.on('end',() => {
body = body.toUpperCase();
response.writeHead(200, defaultCorsHeader) //이건 왜 하는거지?
response.end(body);
})
}//메소드가 POST고, url이 /lower면 소문자로 응답을 돌려줘야 한다
else if(request.method === 'POST' && request.url === '/lower') {
let body = '';
request.on('data', (chunk) => {
body = body + chunk;
})
request.on('end', ()=> {
body = body.toLowerCase();
response.writeHead(200, defaultCorsHeader)
response.end(body);
})
} else { //에러로 처리합니다 bad request
/*response.statusCode = 404; 처음에는 이코드 적음*/
response.writeHead(404, defaultCorsHeader);
response.end();
}
console.log(
`http request method is ${request.method}, url is ${request.url}`
);
//response.writeHead(200, defaultCorsHeader);
//response.end('hello mini-server sprints');
});
server.listen(PORT, ip, () => {
console.log(`http server listen on ${ip}:${PORT}`);
});
const defaultCorsHeader = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Max-Age': 10
};