본문 바로가기
SpringBoot Server/API

API 웹페이지 구현하기 - 웹 개발의 기본 요소와 CORS 설정

by ssury94 2025. 1. 7.


웹 개발은 HTML, CSS, JavaScript의 세 가지 주요 요소로 구성됩니다. 

1. HTML (HyperText Markup Language)

HTML은 웹 페이지의 구조를 정의하는 마크업 언어입니다.

웹사이트의 뼈대를 구성하며, 다양한 태그를 사용해 텍스트, 이미지, 비디오 및 링크 등을 배치합니다.

현재 사용되는 HTML5는 이전 버전보다 많은 기능을 제공하여 더 다양한 웹사이트를 제작할 수 있습니다.

 

기본 구조 예시:

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>웹 페이지 제목</title>
</head>
<body>
    <h1>안녕하세요!</h1>
    <p>이것은 HTML로 작성된 웹 페이지입니다.</p>
</body>
</html>

2. CSS (Cascading Style Sheets)

CSS는 HTML로 작성된 웹 페이지에 스타일을 입히는 언어입니다.

글꼴, 색상, 레이아웃 등을 조정하여 시각적인 효과를 제공합니다.

CSS는 웹 페이지의 디자인을 담당하며, 사용자가 보는 화면의 외관을 결정합니다.
기본 스타일 예시:

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}

h1 {
    color: #333;
}

 

3. JavaScript

JavaScript는 웹 페이지에 동적인 기능과 상호작용을 추가하는 프로그래밍 언어입니다. 

사용자와의 인터랙션을 처리하고, 버튼 클릭이나 폼 제출과 같은 이벤트를 관리합니다.
기본 스크립트 예시:

document.getElementById("myButton").onclick = function() {
    alert("버튼이 클릭되었습니다!");
};

 

 

CORS 설정

 애플리케이션이 다른 출처에서 리소스를 요청할 때 CORS 정책이 필요합니다. 

CORS는 보안상의 이유로 브라우저가 다른 도메인에서 요청하는 것을 제한하는 메커니즘입니다. 

Spring Boot에서는 @CrossOrigin 어노테이션을 사용하여 CORS를 설정할 수 있습니다.


CORS 설정 예시:

import com.marurun66.orderjpa2.dto.OrderListResponse;
import com.marurun66.orderjpa2.dto.OrderRequest;
import com.marurun66.orderjpa2.dto.OrderResponse;
import com.marurun66.orderjpa2.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@CrossOrigin(origins = "*") // 모든 도메인에서 접근 가능
@RestController
public class OrderController {
    @Autowired
    OrderService orderService;


    // 오더 생성
    @PostMapping("/orders")
    public ResponseEntity<Object> createOrder(@RequestBody OrderRequest orderRequest) {
        orderService.createOrder(orderRequest);
        return ResponseEntity.status(201).build();
    }


위의 코드에서 @CrossOrigin(origins = "*")는 모든 출처에서 API에 접근할 수 있도록 허용합니다. 

개발 중에는 유용하지만, 프로덕션 환경에서는 특정 출처만 허용하는 것이 좋습니다.

 

 

 

 

HTML, CSS,JavaScript로 구현한 페이지화면

더보기

<!DOCTYPE html>

<html lang="ko">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>새 주문 생성</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            max-width: 500px;

            margin: 0 auto;

            padding: 20px;

        }

        h1 {

            color: #333;

        }

        form {

            display: flex;

            flex-direction: column;

        }

        label {

            margin-top: 10px;

        }

        input {

            padding: 5px;

            margin-top: 5px;

        }

        button {

            margin-top: 20px;

            padding: 10px;

            background-color: #4CAF50;

            color: white;

            border: none;

            cursor: pointer;

        }

        button:hover {

            background-color: #45a049;

        }

        #result {

            margin-top: 20px;

            padding: 10px;

            border: 1px solid #ddd;

            display: none;

        }

    </style>

</head>

<body>

    <h1>새 주문 생성</h1>

    <form id="orderForm">

        <label for="productName">상품명:</label>

        <input type="text" id="productName" required>

 

        <label for="quantity">수량:</label>

        <input type="number" id="quantity" min="1" required>

 

        <label for="totalPrice">총 가격:</label>

        <input type="number" id="totalPrice" min="0" step="0.01" required>

 

        <button type="submit">주문 생성</button>

    </form>

 

    <div id="result"></div>

 

    <script>

        document.getElementById('orderForm').addEventListener('submit', function(e) {

            e.preventDefault();

 

            const productName = document.getElementById('productName').value;

            const quantity = parseInt(document.getElementById('quantity').value);

            const totalPrice = parseFloat(document.getElementById('totalPrice').value);

 

            // 유효성 검사

            if (productName.trim() === '' || quantity < 1 || totalPrice < 0) {

                alert('입력값을 확인해주세요.');

                return;

            }

 

            const orderData = {

                productName: productName,

                quantity: quantity,

                totalPrice: totalPrice

            };

 

            fetch('http://localhost:8080/orders', {

                method: 'POST',

                headers: {

                    'Content-Type': 'application/json',

                },

                body: JSON.stringify(orderData)

            })

            .then(response => {

                if (response.status === 201) {

                    document.getElementById('result').style.display = 'block';

                    document.getElementById('result').textContent = '주문이 성공적으로 생성되었습니다.';

                    document.getElementById('orderForm').reset();

                } else {

                    throw new Error('주문 생성에 실패했습니다.');

                }

            })

            .catch(error => {

                alert(error.message);

            });

        });

    </script>

</body>

</html>