CORS 설정
- CORS (Cross-Origin Resource Sharing) 설정: 브라우저가 최초 접속한 도메인과는 상이한 도메인에서 오는 요청을 접근하는 것을 허용하도록 application.yml에 CORS 설정을 추가합니다. 이 설정은 클라이언트가 다른 도메인에서 Gateway에 접근할 때 필요한 것입니다. CORS 설정을 통해 허용된 출처에서 오는 요청만 처리하며, 필요한 경우 인증 헤더(Authorization)를 노출합니다. CORS 정책과 exposedHeaders 설정을 통해서만, 브라우저가 다른 출처로부터 특정 헤더(예: Authorization 헤더)를 노출하도록 할 수 있습니다
- Same-Origin Policy(동일 출처 정책), CORS(교차 출처 리소스 공유) 정책에 의해, 다른 도메인에서 요청을 보낼 때 브라우저는 특정 헤더가 기본적으로 노출되지 않도록 차단할 수 있습니다. 즉, 클라이언트 쪽에서 백엔드의 응답에 있는 Authorization 헤더나 access 헤더에 접근할 수 없게 되는 문제가 생깁니다. 클라이언트의 정보를 보호하려는 목적이 아니라, 서버의 민감한 정보를 악의적인 클라이언트에게 노출되지 않도록 보호하기 위해서입니다
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "http://localhost:3000"
allowedMethods: "*"
allowedHeaders: "*"
exposedHeaders: "Authorization"
allowCredentials: true
동기화 비동기화
동기화
- Form Submission (Method 1): Involves a traditional HTTP request-response cycle where the frontend sends data via form submission, and the backend processes the data and typically returns a new page or a redirect response.
- When you use an HTML form to submit data, the browser sends an HTTP request to the server. This request can be either a GET or POST request, depending on how you configure the form. Here's how it works:
- When you submit a form using the default method (GET), the browser constructs a URL that includes the form data as query parameters and sends it to the server. When you submit a form using the POST method, the form data is included in the body of the HTTP request, not in the URL.
- The action attribute specifies the URL to which the form data will be sent. The method="get" attribute indicates that the form data will be sent as a GET request.
- Submit Button: The <input type="submit"> element sends the form data to the server when clicked.
-
- Parameter: The name attribute of tag.
- Value: The data entered or selected by the user in the form control.
-
<!-- Form with action attribute set to the target page URL and using POST method -->
<form action="your-target-page.jsp" method="post">
<input type="text" name="query" placeholder="Enter your query">
<input type="submit" value="Submit">
</form>
비동기화
- AJAX (Asynchronous JavaScript and XML) Calls (Method 2): Involve JavaScript making asynchronous HTTP requests to the backend, which processes these requests and sends back data (often in JSON format), which JavaScript then uses to allows web pages to be updated asynchronously by exchanging data with a server behind the scenes.
- Request Type:
- Method 1: Synchronous, causing the browser to navigate to a new page or reload the current page upon submission. form 전송의 경우에는 url이 새로운 dir로 변하면서 페이지 리로딩이 필요하다.
- Method 2: Asynchronous, allowing data to be sent and received in the background without affecting the display or behavior of the existing page.
- HTML5의 history API를 사용해서 query parameter가 url에 추가되더라도 새로 newpage Reloading없이 url을 발송시킬 수 있다. 그리고 javascript의 fetch를 통해서 동적으로 데이터를 발송하고 부분적으로 화면을 변경할 수 있다. 때문에 pushState와 fetch request는 항상 같이 관리된다.
var newUrl = `index.jsp?LAT=${encodeURIComponent(LAT)}&LNT=${encodeURIComponent(LNT)}`;
window.history.pushState({path: newUrl}, '', newUrl);
fetch(newUrl, {
method: 'get', headers: {'Content-Type': 'application/json'}
}).then(response => {
// Optionally check if the request was successful
if (response.ok) {
console.log("Data was successfully sent to the server.");
} else {
console.error("Failed to send data.");
}
}).catch(error => console.error('Error', error));
}
- User Experience:
- Method 1: Can be less fluid, as it involves a full page reload.
- Method 2: Provides a smoother experience by updating parts of the web page without a reload.
- Flexibility in Handling Responses:
- Method 1: Typically handles responses by loading a new HTML page or by redirecting the user.
- Method 2: Allows for dynamic updates to the current page based on the response data, which can be handled entirely in JavaScript.
랜더링 전략별 백엔드 고려사항
1. SPA (Single Page Application / CSR)
리액트 앱이 브라우저에서 실행된 후 데이터를 요청하는 방식입니다.
- API 특징: "잘게 쪼개진 순수 데이터(JSON) API"
- 데이터 구조: 화면 전체 정보가 아니라, 특정 기능에 필요한 최소한의 데이터만 줍니다. (예: GET /api/user/profile)
- 호출 빈도: 매우 높습니다. 페이지 하나를 그리기 위해 프로필 API, 알림 API, 메뉴 API 등을 병렬로 여러 번 호출합니다.
- 백엔드 최적화 포인트: * 동시 다발적인 작은 요청이 많으므로 Connection Pool 관리와 Redis 캐싱이 중요합니다.
- 여러 API를 호출하는 오버헤드를 줄이기 위해 **API Composition(여러 데이터를 하나로 묶어주는 API)**을 고려하기도 합니다.
2. SSR (Server Side Rendering / Next.js 등)
서버(Node.js)가 페이지를 그리기 위해 백엔드에 데이터를 요청하는 방식입니다.
- API 특징: "한 번에 다 담은 보따리(Massive JSON) API"
- 데이터 구조: 사용자가 페이지에 접속했을 때 화면에 보여야 할 모든 초기 데이터를 하나의 큰 객체로 묶어서 줍니다. (예: GET /api/pages/dashboard-summary)
- 호출 빈도: 낮습니다. 서버 대 서버(Server-to-Server) 통신이므로 한두 번의 굵직한 호출로 끝납니다.
- 백엔드 최적화 포인트: * 응답 데이터가 크기 때문에 JSON 직렬화/역직렬화 비용과 네트워크 페이로드 크기를 신경 써야 합니다.
- 복잡한 조인이 발생하므로 DB 쿼리 최적화가 최우선입니다.
3. BFF (Backend For Frontend) - 상화님이 주목할 방식
최근 대형 플랫폼에서 가장 많이 쓰는 방식입니다. 프론트엔드 바로 앞에 전용 API 게이트웨이를 두는 전략입니다.
- 배경: 프론트엔드 기기가 모바일이냐, PC냐에 따라 필요한 데이터가 다릅니다.
- 작동 방식: 프론트가 BFF에게 "화면 그려야 해"라고 한 번만 말하면, BFF가 뒤쪽의 마이크로서비스(MSA)들을 대신 찔러서 딱 필요한 형태로 가공해 한 번에 응답합니다.
- 백엔드 최적화 포인트: * 기기별로 최적화된 데이터만 보내므로 네트워크 트래픽을 극단적으로 절약할 수 있습니다.
- 상화님 같은 백엔드 개발자가 이 BFF 계층을 설계할 때 프론트의 요구사항을 가장 깊게 반영하게 됩니다.
4. SSG (Static Site Generation)
빌드 시점에 미리 데이터를 가져와서 HTML을 구워버리는 방식입니다.
- API 특징: "배치(Batch)성 대량 요청"
- 호출 빈도: 배포(Build) 시점에만 폭발적으로 발생하고, 실서비스 중에는 호출이 거의 없습니다.
- 백엔드 최적화 포인트: * 빌드 시점에 API 서버가 죽지 않도록 **Rate Limiting(요청 제한)**이나 Bulk 조회 API를 제공해야 합니다.
5. MPA (Multi-Page Application) - "클래식한 서버 중심 방식"
상화님이 말씀하신 "예전 방식"이자, JSP/Thymeleaf를 사용하는 Spring Boot의 전통적인 모습입니다.
- 동작 방식: 브라우저가 URL을 요청할 때마다 백엔드가 완성된 HTML을 새로 만들어서 던져줍니다.
- API 특징: 별도의 JSON API가 존재하지 않습니다. 데이터는 서버 내부에서 직접 DB를 찔러 가져온 뒤, HTML 템플릿에 버무려집니다.
- 호출 빈도: 페이지 이동 시마다 1번. 하지만 매번 전체 HTML을 다시 받으므로 네트워크 페이로드는 무겁습니다.
- 백엔드 최적화 포인트:
- 서버 사이드 렌더링 부하: 자바 진영에서는 View Engine이 HTML을 생성하는 CPU 연산 비용이 듭니다.
- 세션 관리: 페이지 이동 시마다 상태가 초기화되므로 HttpSession 등을 통한 상태 유지가 필수적입니다.
'개발기술 > 프론트엔드' 카테고리의 다른 글
| React (0) | 2025.11.18 |
|---|---|
| 웹 브라우저 API (0) | 2025.02.26 |
| 왜 백엔드 개발자가 프론트엔드 코드를 알아야 할까? (0) | 2025.02.12 |
| 톰캣 설치를 통한 JSP 사용법 (1) | 2024.07.01 |
| HTML, CSS (1) | 2024.06.09 |