오즈코딩스쿨 초격차캠프 백엔드 11일차

Hyemin Kim·2023년 12월 21일
0

✅ 1. 웹 성능 최적화 방법

웹 성능 최적화는 웹 페이지의 로딩 시간을 단축하고 사용자 경험을 향상시키는 것을 목표로 합니다. 아래는 웹 성능 최적화를 위한 주요 방법들입니다:

  1. 이미지 최적화:

    • 이미지를 최적화하고 필요하지 않은 이미지를 제거합니다.
    • Lazy loading을 활용하여 페이지가 로딩될 때까지 이미지를 로드하지 않습니다.
  2. 파일 압축:

    • CSS, JavaScript, HTML 파일을 압축하여 전송 시간을 최소화합니다.
    • Gzip 등의 압축 알고리즘을 사용합니다.
  3. 브라우저 캐싱 활용:

    • 정적 파일을 캐싱하여 반복된 요청에서 로딩 시간을 줄입니다.
    • Cache-Control 헤더 및 Expires 헤더를 설정합니다.
  4. 비동기 로딩:

    • 필요한 자원을 비동기적으로 로드하여 초기 페이지 로딩 속도를 향상시킵니다.
    • defer 및 async 속성을 사용하여 스크립트를 비동기적으로 로드합니다.
  5. CDN 사용:

    • 콘텐츠 전송 네트워크를 통해 컨텐츠를 더 빠르게 전송합니다.
    • 전 세계에 분산된 서버를 통해 콘텐츠를 제공합니다.
  6. 렌더링 최적화:

    • CSS와 JavaScript를 최소화하고, 불필요한 렌더링을 피하도록 합니다.
    • Critical CSS를 최적화하여 초기 렌더링에 필요한 스타일만 포함합니다.
  7. 서버 사이드 렌더링 (SSR):

    • SSR을 사용하여 서버에서 페이지를 렌더링하여 초기 로딩 성능을 개선합니다.
    • 검색 엔진 최적화에도 도움이 됩니다.
  8. 이벤트 위임 활용:

    • 이벤트 핸들러를 최상위 요소에 등록하여 이벤트 버블링을 활용합니다.
  9. 리소스 크기 최적화:

    • 불필요한 리소스를 최소화하고, 최적화된 폰트 및 CSS 프레임워크를 사용합니다.
  10. 웹폰트 최적화:

    • 웹폰트를 최적화하여 페이지 로딩을 빠르게 합니다.
    • 필요한 글꼴만 로드하고, 폰트 디스플레이 속성을 사용하여 폰트가 로드될 때까지 기본 글꼴을 사용합니다.

이러한 최적화 기법들을 조합하여 웹 페이지의 성능을 향상시킬 수 있습니다. 성능 테스팅 도구를 사용하여 최적화의 효과를 모니터링하고 개선할 수 있습니다.

- How to optimize Web performance

Optimizing web performance involves various techniques and best practices to reduce page load times and enhance the user experience. Here are some key strategies for optimizing web performance:

  1. Image Optimization:

    • Compress and optimize images to reduce file sizes.
    • Use the appropriate image format (JPEG, PNG, SVG) for different types of images.
    • Lazy loading can be implemented to load images only when they come into the user's viewport.
  2. File Compression:

    • Minify and compress CSS, JavaScript, and HTML files.
    • Use Gzip or Brotli compression to reduce file sizes for faster transmission.
  3. Browser Caching:

    • Leverage browser caching to store static files locally on the user's device.
    • Set appropriate Cache-Control headers and Expires headers.
  4. Asynchronous Loading:

    • Load non-essential resources asynchronously to speed up the initial page load.
    • Use the async and defer attributes for script tags.
  5. Content Delivery Network (CDN):

    • Use a CDN to distribute content across multiple servers, reducing latency for users globally.
    • CDN helps in serving static assets closer to the user's geographical location.
  6. Optimized Rendering:

    • Minimize CSS and JavaScript to reduce render-blocking resources.
    • Optimize critical rendering path and prioritize above-the-fold content.
  7. Server-Side Rendering (SSR):

    • Implement SSR to render pages on the server, improving initial load times.
    • SSR is beneficial for SEO and performance, especially for single-page applications.
  8. Event Delegation:

    • Use event delegation to attach a single event listener to a common ancestor rather than individual elements.
    • Utilize event bubbling to handle events more efficiently.
  9. Resource Size Optimization:

    • Minimize unnecessary resources and prioritize critical resources.
    • Optimize fonts and use font-display property to control font loading behavior.
  10. Web Font Optimization:

    • Optimize web fonts by loading only the necessary font weights and styles.
    • Use the font-display property to control how fonts are displayed during loading.
  11. Reduce HTTP Requests:

    • Minimize the number of HTTP requests by combining and bundling CSS and JavaScript files.
    • Use sprites for small images and reduce the number of external resources.
  12. Web Performance Monitoring:

    • Use performance monitoring tools to analyze and identify performance bottlenecks.
    • Continuously monitor and optimize website performance based on real user data.

By implementing these strategies, web developers can significantly improve the performance of their websites, resulting in faster load times and a better overall user experience.

✅ 2. 네트워크 설명

네트워크는 컴퓨터나 다른 기기들이 서로 연결되어 정보를 주고받을 수 있는 구조를 말합니다. 네트워크는 데이터 통신을 가능케 하며, 이를 통해 사용자들은 리소스를 공유하고 서비스에 접근할 수 있습니다. 아래는 네트워크의 기본 개념과 구성 요소에 대한 설명입니다:

  1. 네트워크의 기본 용어:

    • 노드(Node): 네트워크에 연결된 각각의 장치나 컴퓨터를 말합니다.
    • 링크(Link): 노드 간에 데이터를 전송하는 데 사용되는 물리적인 연결을 나타냅니다.
    • 패킷(Packet): 데이터 전송의 기본 단위로, 작은 크기의 데이터 조각을 말합니다.
  2. 네트워크의 종류:

    • LAN (Local Area Network): 가까운 지역 내에서 컴퓨터 및 기기들이 연결된 네트워크입니다.
    • WAN (Wide Area Network): 지리적으로 분산된 지역을 연결하는 큰 규모의 네트워크입니다.
    • 인터넷(Internet): 여러 개의 LAN 및 WAN이 연결된 전세계적인 규모의 공개 네트워크입니다.
  3. 네트워크 구성 요소:

    • 라우터(Router): 다른 네트워크 간에 데이터를 전송하는 역할을 하는 장비입니다.
    • 스위치(Switch): LAN에서 여러 디바이스 간에 데이터를 전송하는 역할을 하는 장비입니다.
    • 게이트웨이(Gateway): 서로 다른 네트워크 간에 통신을 중개하는 역할을 하는 장비입니다.
    • 모뎀(Modem): 디지털 데이터를 아날로그 신호로 변환하거나 반대로 변환하는 장치입니다.
  4. 프로토콜(Protocol):

    • 네트워크에서 데이터 통신을 위한 규칙과 규약을 말합니다.
    • TCP/IP 프로토콜은 인터넷에서 주로 사용되며, HTTP, HTTPS, FTP 등은 TCP/IP 기반의 프로토콜입니다.
  5. 서비스와 응용:

    • 웹 서비스(Web Service): 인터넷을 통해 서로 다른 시스템 간에 상호 작용할 수 있는 서비스입니다.
    • 이메일 서비스: 전자우편을 주고받을 수 있는 서비스입니다.
    • 파일 공유 서비스: 파일이나 데이터를 다른 사용자와 공유하는 서비스입니다.
  6. 보안 및 관리:

    • 방화벽(Firewall): 네트워크를 보호하기 위해 불법적인 액세스를 차단하는 시스템입니다.
    • VPN(Virtual Private Network): 안전한 방식으로 원격 네트워크에 접속하기 위한 기술입니다.
    • 네트워크 관리(Network Management): 네트워크의 성능을 최적화하고 문제를 해결하는 활동입니다.

네트워크는 현대 사회에서 핵심적인 역할을 하며, 정보 공유, 통신, 원격 작업 등 다양한 기능을 수행합니다.

- Network Description

A network is a system of interconnected computers, devices, and communication channels that enable the exchange of data and resources. Networks play a crucial role in facilitating communication, sharing information, and providing access to services. Here's an overview of key concepts related to networks:

  1. Basic Terminology:

    • Node: Any device or computer connected to the network.
    • Link: The physical or logical connection between nodes used for data transmission.
    • Packet: The basic unit of data transmitted over a network.
  2. Types of Networks:

    • LAN (Local Area Network): A network that connects computers and devices within a limited geographic area, such as a home, office, or campus.
    • WAN (Wide Area Network): A network that spans a larger geographical area, often connecting LANs over long distances.
    • Internet: A global network that interconnects millions of networks worldwide.
  3. Components of a Network:

    • Router: Manages data traffic between different networks.
    • Switch: Connects devices within a LAN and directs data traffic more efficiently than traditional hubs.
    • Gateway: Connects different networks, facilitating communication between them.
    • Modem: Converts digital data to analog signals for transmission over communication lines.
  4. Protocols:

    • Protocol: Rules and conventions governing communication between devices on a network.
    • TCP/IP (Transmission Control Protocol/Internet Protocol): The fundamental suite of protocols for the Internet.
  5. Network Services and Applications:

    • Web Services: Allow systems to communicate and share data over the internet.
    • Email Services: Enable the exchange of electronic messages.
    • File Sharing Services: Facilitate the sharing of files and data among users.
  6. Security and Management:

    • Firewall: A security device that monitors and controls incoming and outgoing network traffic.
    • VPN (Virtual Private Network): Provides a secure way to connect to a private network over the internet.
    • Network Management: Activities aimed at optimizing network performance, troubleshooting issues, and ensuring reliability.
  7. Wireless Networks:

    • Wi-Fi: Enables wireless connectivity within a specific range.
  8. Emerging Technologies:

    • 5G Networks: The fifth generation of mobile networks, offering higher speeds and improved connectivity.
    • IoT (Internet of Things): Interconnected devices that communicate and share data over the internet.

Networks are foundational to modern communication, collaboration, and access to information. They enable the seamless flow of data, supporting various applications and services that enhance our daily lives and business operations.

✅ 3. CSRF Attack이란?

CSRF(Cross-Site Request Forgery) 공격은 웹 애플리케이션에서 사용자가 의도하지 않은 요청을 실행하도록 속이는 공격입니다. 이러한 공격에서 공격자는 희생자의 인증 정보를 이용하여 악의적인 요청을 보냅니다. CSRF 공격은 주로 웹 애플리케이션에서 사용되는 세션 인증을 이용하여 이루어지며, 공격자는 희생자가 이미 인증된 상태일 때 공격을 시도합니다.

CSRF 공격의 주요 특징과 동작 방식은 다음과 같습니다:

  1. 사전 조건:

    • 희생자는 악의적인 웹 사이트를 방문하거나 악의적인 이메일을 클릭하는 등의 행동을 취해야 합니다.
  2. 인증 정보 이용:

    • 희생자가 이미 로그인되어 있는 경우, 그 세션 정보를 이용하여 공격자는 희생자 대신 요청을 보낼 수 있습니다.
  3. 악의적인 요청 전송:

    • 공격자는 희생자가 의도하지 않은 악의적인 요청을 서버로 전송합니다.
    • 예를 들어, 은행 계좌 이체, 비밀번호 변경 등의 중요한 작업을 요청할 수 있습니다.
  4. 동작 원리:

    • CSRF는 웹 브라우저의 쿠키와 세션을 이용하여 동작합니다. 희생자의 브라우저는 인증된 상태로 악의적인 요청을 서버로 보내게 됩니다.
  5. 방어 기법:

    • CSRF 토큰 사용: 웹 애플리케이션에서는 사용자의 요청에 대한 고유한 토큰을 생성하고 이를 요청과 함께 전송하여 유효성을 검사합니다.
    • SameSite 쿠키 속성: SameSite 쿠키 속성을 이용하여 요청의 출처를 제한함으로써 CSRF를 방지할 수 있습니다.

CSRF 공격은 사용자가 웹 애플리케이션에 로그인되어 있는 상태에서 발생할 수 있기 때문에, 적절한 보안 조치를 취하여 사용자를 보호하는 것이 중요합니다.

- What is CSRF Attack?

CSRF (Cross-Site Request Forgery) attack is a type of security vulnerability in web applications where an attacker tricks a user's browser into performing an undesired action on a web application in which the user is authenticated. The attack takes advantage of the trust that a web application has in the user's browser and their active session.

Here is a breakdown of how a CSRF attack typically works:

  1. Preconditions:

    • The victim (user) must be authenticated and have an active session on a targeted web application.
  2. Malicious Link or Content:

    • The attacker crafts a malicious link or embeds malicious content in a website, email, or other communication channels that the victim accesses.
  3. User Interaction:

    • The victim clicks on the malicious link, possibly without realizing the hidden malicious intent.
  4. Unauthorized Action:

    • The victim's browser, now acting on behalf of the authenticated user, unknowingly sends a request to the targeted web application to perform an action.
  5. Exploitation:

    • The targeted web application, trusting the authenticated session, processes the request as if it came from the legitimate user, leading to unintended and potentially harmful actions.

Common examples of CSRF attacks include unauthorized fund transfers, changes to account settings, or any action that a user can perform within the authenticated session.

Prevention Techniques:
To defend against CSRF attacks, web developers can implement the following techniques:

  1. CSRF Tokens:

    • Include anti-CSRF tokens in forms or requests, which are unique and tied to the user's session. These tokens must be submitted with each request, and the server checks their validity.
  2. SameSite Cookie Attribute:

    • Set the SameSite attribute on cookies to restrict when cookies are sent with cross-site requests, providing an additional layer of defense.
  3. Referrer Policy:

    • Employ strict referrer policies to control which websites can access certain resources, reducing the risk of unauthorized requests.

By implementing these preventive measures, web applications can significantly reduce the risk of CSRF attacks and enhance overall security.

✅ 4. 비동기 처리를 다루는 방법

비동기 처리(Asynchronous Programming)를 다루는 방법은 여러 가지가 있으며, 주로 JavaScript에서 가장 많이 사용됩니다. 비동기 처리는 특히 웹 개발에서 서버와의 통신, 이벤트 처리, 파일 읽기/쓰기 등과 같은 상황에서 중요합니다. 아래는 비동기 처리를 다루는 주요 방법들입니다:

  1. 콜백 함수 (Callback Functions):

    • 함수를 다른 함수의 인자로 전달하여 비동기 동작이 완료되면 해당 함수(콜백 함수)가 실행되도록 하는 방법입니다.

    • 예시:

      function fetchData(callback) {
        // 비동기 동작
        setTimeout(function() {
          console.log("Data Fetched!");
          callback();
        }, 1000);
      }
      
      fetchData(function() {
        console.log("Callback function executed.");
      });
  2. Promise:

    • Promise는 비동기 작업이 성공 또는 실패할 때의 결과를 나타내는 객체입니다.

    • thencatch 메서드를 사용하여 성공 또는 실패 시 수행할 작업을 지정할 수 있습니다.

    • 예시:

      function fetchData() {
        return new Promise(function(resolve, reject) {
          // 비동기 동작
          setTimeout(function() {
            console.log("Data Fetched!");
            resolve();
          }, 1000);
        });
      }
      
      fetchData().then(function() {
        console.log("Promise resolved.");
      });
  3. Async/Await:

    • Async/Await는 Promise를 기반으로 한 비동기 코드를 더 간결하게 작성할 수 있는 방법입니다.

    • async 함수 내에서 await 키워드를 사용하여 비동기 작업이 완료될 때까지 대기합니다.

    • 예시:

      async function fetchData() {
        return new Promise(function(resolve) {
          setTimeout(function() {
            console.log("Data Fetched!");
            resolve();
          }, 1000);
        });
      }
      
      async function fetchDataAndLog() {
        await fetchData();
        console.log("Async/Await: Data fetched and logged.");
      }
      
      fetchDataAndLog();
  4. Event Listeners:

    • 이벤트 처리에서 비동기 처리는 주로 이벤트 리스너를 통해 이루어집니다. 사용자의 행동에 따라 특정 동작을 수행할 때 비동기적으로 처리됩니다.
    • 예시:
      document.getElementById("myButton").addEventListener("click", function() {
        console.log("Button Clicked!");
      });

이러한 방법들은 JavaScript에서 주로 사용되며, 비동기 처리의 성격과 요구 사항에 따라 선택할 수 있습니다. 최근에는 Async/Await가 코드 가독성과 작성의 편의성 면에서 많이 사용되고 있습니다.

- How to handle asynchronous processing

Handling asynchronous processing in programming, especially in JavaScript, involves various techniques and patterns. Here are some common approaches:

  1. Callback Functions:

    • Use callback functions to handle asynchronous operations. Pass a function as an argument to be executed once the asynchronous operation is complete.

    • Example:

      function fetchData(callback) {
        // Asynchronous operation
        setTimeout(function() {
          console.log("Data Fetched!");
          callback();
        }, 1000);
      }
      
      fetchData(function() {
        console.log("Callback function executed.");
      });
  2. Promises:

    • Promises provide a cleaner way to handle asynchronous operations. They represent a value that might be available now, or in the future, or never.

    • Example:

      function fetchData() {
        return new Promise(function(resolve, reject) {
          // Asynchronous operation
          setTimeout(function() {
            console.log("Data Fetched!");
            resolve();
          }, 1000);
        });
      }
      
      fetchData().then(function() {
        console.log("Promise resolved.");
      });
  3. Async/Await:

    • Async/Await is a syntactic sugar built on top of promises, making asynchronous code look and behave like synchronous code.

    • Example:

      async function fetchData() {
        return new Promise(function(resolve) {
          // Asynchronous operation
          setTimeout(function() {
            console.log("Data Fetched!");
            resolve();
          }, 1000);
        });
      }
      
      async function fetchDataAndLog() {
        await fetchData();
        console.log("Async/Await: Data fetched and logged.");
      }
      
      fetchDataAndLog();
  4. Event Listeners:

    • For asynchronous operations triggered by events (e.g., user interactions), use event listeners to handle the asynchronous code.
    • Example:
      document.getElementById("myButton").addEventListener("click", function() {
        console.log("Button Clicked!");
      });
  5. Callbacks in Node.js (CommonJS pattern):

    • In Node.js, the CommonJS pattern is often used, where functions that perform asynchronous operations take callback functions as parameters.

    • Example:

      const fs = require("fs");
      
      fs.readFile("example.txt", "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
      });

Choose the approach that best fits your application's requirements and the readability you desire in your code. Async/Await is a modern and widely adopted pattern, especially for handling asynchronous operations in a more synchronous-looking style.

✅ 5. 클로저란?

클로저(Closure)는 프로그래밍 언어에서 함수와 그 함수가 선언된 렉시컬 환경(Lexical Environment)의 조합입니다. 클로저는 함수가 자신이 선언된 스코프 밖의 변수에 접근할 수 있는 메커니즘을 제공합니다.

클로저는 다음과 같은 특징을 가지고 있습니다:

  1. 변수 캡처 (Variable Capture): 클로저는 자신이 정의된 스코프에서 벗어난 외부 변수에 접근할 수 있습니다. 이는 함수가 선언될 당시의 환경을 기억하고 있다는 의미로 설명됩니다.

  2. 지속성 (Persistence): 클로저가 외부 변수를 참조하고 있을 때, 해당 변수는 클로저가 존재하는 한 메모리에서 사라지지 않습니다. 이는 함수가 호출될 때마다 해당 함수에서 사용하는 외부 변수의 값이 유지됨을 의미합니다.

클로저의 예시를 살펴보겠습니다:

function outerFunction(x) {
  // 내부 함수인 innerFunction이 클로저입니다.
  function innerFunction(y) {
    console.log(x + y);
  }
  return innerFunction;
}

// outerFunction을 호출하면서 x에 10을 전달한 결과를 클로저로 반환받습니다.
const closureExample = outerFunction(10);

// closureExample은 여전히 outerFunction의 스코프에 접근할 수 있습니다.
closureExample(5); // 결과: 15

이 예시에서 innerFunction은 외부 함수인 outerFunction의 매개변수 x에 접근할 수 있는 클로저가 됩니다. 클로저를 통해 외부 변수에 접근하고 조작함으로써 함수의 유연성과 모듈성을 높일 수 있습니다.

- What is a closure?

A closure is a programming concept in which a function retains access to variables from its containing (enclosing) lexical scope even after the function has finished executing. In simpler terms, a closure allows a function to "remember" the environment in which it was created, and it has access to variables from that environment, even if the function is called outside that environment.

Key points about closures:

  1. Variable Capture: Closures capture the variables of the outer (enclosing) function, allowing the inner function to access and manipulate them.

  2. Lexical Scoping: Closures work based on lexical scoping, which means they remember the variable scope where they were created, not where they are executed.

  3. Persistence: Closures keep a reference to the variables they capture, even if the outer function has completed execution. This provides a form of data persistence.

Here's a simple JavaScript example:

function outerFunction(x) {
  // innerFunction is a closure that captures the 'x' variable
  function innerFunction(y) {
    console.log(x + y);
  }
  return innerFunction;
}

// Create a closure by calling outerFunction with '10' and storing the result
const closureExample = outerFunction(10);

// The closure (innerFunction) retains access to the 'x' variable
closureExample(5); // Outputs: 15

In this example, innerFunction is a closure because it has access to the x variable from its containing scope (outerFunction). Closures are commonly used in various programming languages to implement data encapsulation, private variables, and callback functions.

✅ 6. 스코프란?

스코프(Scope)는 변수와 함수의 유효 범위를 나타내는 개념입니다. 즉, 어떤 부분에서 변수나 함수에 접근할 수 있는지를 정의합니다. 스코프는 코드에서 변수의 가시성과 생명주기를 결정하며, 코드의 유지보수성과 에러 방지에 중요한 역할을 합니다.

일반적으로 스코프는 두 가지 종류로 나뉩니다:

  1. 전역 스코프 (Global Scope): 전역 스코프는 코드 어디에서든지 접근할 수 있는 최상위 스코프입니다. 전역 스코프에 선언된 변수는 프로그램 전체에서 사용할 수 있습니다.

  2. 지역 스코프 (Local Scope): 지역 스코프는 특정 코드 블록 내에서 변수나 함수가 유효한 범위를 나타냅니다. 함수 내에서 선언된 변수는 해당 함수 내부에서만 접근 가능하며, 블록 내에서 선언된 변수는 해당 블록 내에서만 접근 가능합니다.

스코프는 렉시컬 스코프(Lexical Scope) 또는 정적 스코프(Static Scope)라고도 불립니다. 이는 코드가 작성된 위치에 따라 스코프가 결정된다는 의미입니다. 함수가 어디에 선언되었는지에 따라 함수가 참조하는 변수의 스코프가 정해지는 것을 의미합니다.

예시를 통해 살펴보겠습니다:

// 전역 스코프
const globalVariable = "I am global";

function outerFunction() {
  // outerFunction 스코프
  const outerVariable = "I am outer";

  function innerFunction() {
    // innerFunction 스코프
    const innerVariable = "I am inner";
    console.log(globalVariable);  // 접근 가능
    console.log(outerVariable);  // 접근 가능
    console.log(innerVariable);  // 접근 가능
  }

  innerFunction();
}

outerFunction();

이 예제에서 globalVariable은 전역 스코프에 선언되어 어디에서든 접근 가능하고, outerVariableouterFunction 스코프에 선언되어 해당 함수 내에서만 접근 가능합니다. innerFunction 내에서는 모든 변수에 접근할 수 있습니다.

- What is Scope?

Scope refers to the context in which variables and functions are defined and accessed in a programming language. It defines the visibility and accessibility of these variables and functions within a program. In simpler terms, scope determines where in your code a particular variable or function is available for use.

There are two main types of scope:

  1. Global Scope:

    • Variables or functions declared in the global scope are accessible from any part of the code, including within functions.
    • They have a global context and are often referred to as global variables or functions.
    • Global variables are declared outside of any function or block.
    const globalVariable = "I am global";
    
    function exampleFunction() {
      console.log(globalVariable);  // Accessible within functions
    }
    
    console.log(globalVariable);  // Accessible globally
  2. Local Scope:

    • Variables or functions declared within a function or block have local scope.
    • They are only accessible within the function or block where they are defined.
    • Local variables can have the same name as variables in other scopes without conflict.
    function exampleFunction() {
      const localVariable = "I am local";
      console.log(localVariable);  // Accessible only within the function
    }
    
    console.log(localVariable);  // Error: localVariable is not defined

Scope is crucial for managing variable names, avoiding naming conflicts, and ensuring that variables are only used where they are intended. The concept of scope is closely related to the idea of lexical scoping, where the scope of a variable is determined by its location in the source code.

profile
Full Stack Web Developer

0개의 댓글