본문 바로가기

개발기술/Web Dev

프론트엔드 연계 관련 지식

 

백엔드/프론트 엔드 관계

  • 백엔드는 프론트엔드 서버에 응답을 보내는 것이 아니라, 직접 브라우저로 데이터를 전송합니다. 즉, 브라우저에서 자바스크립트 코드가 해당 응답을 처리하게 되는데, 이때 CORS 정책이 적용됩니다.
  • . 유저의 브라우저가 내려받은 JavaScript가 백엔드의 Authorization 헤더에 접근할 수 있도록 설정하는 것이 핵심입니다.

 

 


4. 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.
        1. Parameter: The name attribute of tag.
        2. 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.