본문 바로가기

Node.js

23. cors(Cross-Origin Resource Sharing)

cors(Cross-Origin Resource Sharing)

- 웹 애플리케이션에서 다른 도메인(Origin) 간의 HTTP 요청을 제어하는 보안 기능

- 브라우저는 보안상의 이유로, 웹 페이지에서 스크립트를 통한 다른 도메인으로의 HTTP 요청을 제한하고 있는데, 이를 CORS 정책이라고 합니다.

 


cors 예제

 

cors.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>프론트엔드</title>
</head>
<body>
    <h2>6-cos</h2>
    <p>프론트엔드로 사용할 6-cos.html</p>
    <script>
        fetch("http://localhost:8080/", {method:"GET"}) // fetch를 사용하여 http://localhost:8080/ 주소로 GET 요청을 보냄 
            .then(console.log) // 요청이 성공적으로 완료되면 응답객체 출력
            .catch(console.error); // 요청이 실패하면 발생한 에러를 콘솔에 출력
    </script>
</body>
</html>

 

 

cors를 사용하지 않았을 때

import express from 'express';

const app = express();

app.use((req, res, next) => {
    // 브라우저 정책때문에 'Access-Control-Allow-Origin'을 헤더에 넣어주지 않으면 에러남
    res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:5500/6-cos.html');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, DELETE'); // 메소드 요청을 허용함
    next();
});

app.get('/', (req, res) => {
    res.send('Welcome!');
});

app.listen(8080)

 

cors 사용

import express from "express";
import morgan from "morgan";
import cors from "cors";

const app = express();

// morgan 미들웨어 사용
// morgan : 날짜, HTTP 메소드, URL, 응답 상태 코드, 응답 본문의 크기, 응답 시간 등의 정보를 로깅함
app.use(morgan("common"));
// cors 미들웨어 사용
app.use(cors());

app.get('/', (req, res) => {
    console.log("/ get으로 메인페이지 호출!");
    res.send("Welcome");
});

app.listen(8080);

 

 

cors.html 실행

 

터미널 출력

 

 

'Node.js' 카테고리의 다른 글

22. express.static  (0) 2023.04.23
21. 라우팅(routing)  (0) 2023.04.22
20. error handling  (0) 2023.04.22
19. GET, DELETE, POST method  (0) 2023.04.22
18. express  (0) 2023.04.22