Web API(Web Application Programming Interface)
MDN(Mozilla Developer Network)의 정의
"Web APIs are a set of APIs available in web browsers for building web applications. These APIs allow web developers to interact with browser features and external services using JavaScript."
Web API는 웹 브라우저에서 제공하는 API 집합이며, JavaScript를 사용하여 브라우저의 기능을 조작할 수 있도록 지원한다.
JavaScript 브라우저(Web API) 기능 사용
웹 브라우저가 제공하는 API (DOM 조작, 이벤트, AJAX 등) 중 이 API들은 백엔드 개발자가 직접 테스트하거나 프론트엔드와의 연동을 이해하기 위해 기본적인 구현을 할 줄 알아야 한다.
Web API | 설명 | 구현 필요성 |
네트워크 API (fetch(), XMLHttpRequest) | API 요청을 보내고 응답 받기 | ⭐ 필수 |
타이머 API (setTimeout(), setInterval()) | 비동기 작업 및 일정 실행 | ⭐ 필수 |
스토리지 API (localStorage, sessionStorage) | 클라이언트 측 데이터 저장 방식 | 🎯 기본 구현 필요 |
DOM API (document.querySelector()) | HTML 요소 조작 | 🎯 기본 구현 권장 |
이벤트 리스너 API (addEventListener()) | 사용자 입력 감지 | 🎯 기본 구현 권장 |
웹 워커 API (Worker()) | 백그라운드 작업 실행 | ❌ 몰라도 됨 |
WebRTC API (getUserMedia()) | 실시간 스트리밍 |
DOM API
DOM(Document Object Model)은 브라우저가 제공하는 API 중 하나 HTML이나 XML 문서를 프로그래밍적으로 제어할 수 있도록 구조화한 객체 모델입니다. 브라우저에서 HTML을 해석하여 DOM은 HTML 요소를 노드(Node) 형태로 표현한 트리 구조입니다.
왜 DOM이 필요한가?
1. 브라우저 관점:
- 브라우저가 HTML/XML 문서를 구조화하여 이해하고 렌더링하기 위해 DOM이 필요합니다.
- DOM은 브라우저 내부에서 HTML을 처리하는 기본적인 데이터 모델입니다.
2. 프로그래밍 언어 관점:
- 프로그래밍 언어가 DOM을 통해 문서의 구조와 내용을 동적으로 제어할 수 있게 하기 위해 DOM이 필요합니다.
- DOM API는 프로그래밍 언어와 브라우저가 문서를 공유하는 "공통 언어" 역할을 합니다.
주요 구성 요소 (객체)
- 문서 노드 (Document Node) : HTML 문서 전체를 의미 (document 객체)
- 요소 노드 (Element Node) : HTML 태그 (<h1>, <p>, <div> 등)
- 속성 노드 (Attribute Node) : 요소의 속성 (id, class, href 등)
- 텍스트 노드 (Text Node) : 태그 내부의 텍스트 내용
- 주석 노드 (Comment Node) : <!-- 주석 -->
DOM 요소 선택하기
- 요소 : HTML 문서에서 태그로 표현되는 하나의 객체. <div>, <p>, <img>, <button> 등이 모두 요소.
- document.getElementById("id") : 해당 id 속성을 가진 단일 요소를 찾음
- document.getElementsByClassName("class") : 해당 class 이름을 가진 모든 요소들을 찾음
-
document.getElementsByTagName("tag") : HTML에서 <p>와 같은 태그를 사용하는 요소들을 찾음
이벤트 리스너 API
- 마우스 이벤트 (Mouse Events) : onclick, ondblclick, onmouseover, onmouseout, onmousedown, onmouseup, onmousemove
- 키보드 이벤트 (Keyboard Events) : onkeydown, onkeyup, onkeypress
- 문서/창 이벤트 (Window Events) : onload, onresize, onscroll, onunload
- 폼(Form) 이벤트 : onchange, onfocus, onblur, onsubmit
네트워크 API
네트워크 API(Network API)는 서버와 데이터를 주고받을 때 사용하는 Web API입니다. 브라우저가 제공하는 비동기 HTTP 요청 기능을 활용하여, 백엔드 API와 데이터를 주고받을 수 있도록 합니다.
- fetch() : 최신 표준 네트워크 API로, 비동기적으로 HTTP 요청을 보낼 수 있는 Promise 기반 API입니다
- 기본적으로 GET, POST, PUT, DELETE 등 HTTP 메서드를 지원하며, 요청 헤더 및 본문을 설정할 수도 있습니다.
- .기본적으로 Promise를 반환하므로, .then() 또는 async/await을 사용할 수 있습니다.
- fetch("https://api.example.com/data") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error:", error));
Window API
- alert("TexttoDisplay") : 경고창을 메세지와 함께 출력한다. ex) <input type="button" onclick="alert("hello")>
- window.alert() : 사실은 window가 생략되어있음
- typeof() : 데이터의 타입을 반환함
- prompt() : 사용자가 프롬프트에 입력한 값을 반환함
쿠키
- 쿠키(Cookie)**란, 웹사이트가 사용자의 브라우저에 저장하는 작은 데이터 조각입니다. 쿠키는 클라이언트(브라우저)와 서버 간의 상태를 유지하기 위해 사용됩니다. 특히, 인증 정보를 저장하여 사용자가 로그인 상태를 유지하는 데 활용됩니다.
- 쿠키는 서버가 클라이언트(브라우저)에 저장하도록 설정할 수 있으며, 이후 요청마다 자동으로 서버에 포함됩니다.
- 쿠키 생성 과정
- 1.사용자가 https://example.com에 접속.
- 2. 서버가 응답 시 Set-Cookie 헤더를 포함하여 쿠키를 브라우저에 저장하도록 요청.
- 3. 이후 브라우저는 example.com으로 요청을 보낼 때 자동으로 쿠키를 포함.
HTTP/1.1 200 OK
Set-Cookie: sessionId=abc123; Path=/; HttpOnly; Secure
- 자동으로 쿠키가 포함되는 조건
- 브라우저는 "쿠키가 설정된 도메인"과 "보내는 요청의 도메인"이 같을 때, 자동으로 쿠키를 포함합니다.
- 1. 쿠키의 도메인(Domain)이 요청의 도메인과 일치해야 함.
- 2. 쿠키의 Path가 요청된 URL과 일치해야 함.
- 3. 쿠키의 Secure 옵션이 설정된 경우, HTTPS에서만 전송됨.
- 4. 쿠키의 HttpOnly 옵션이 설정된 경우, JavaScript에서 접근 불가능.
- 5. 쿠키의 SameSite 설정에 따라, 다른 출처에서 요청할 때 포함 여부가 달라짐
- 쿠키관련속성 : 쿠키는 보안과 기능을 위해 다양한 속성을 가질 수 있습니다.
속성 | 설명 |
Domain | 쿠키가 적용될 도메인 (example.com) |
Path | 특정 경로에서만 쿠키 전송 가능 (/api/) |
HttpOnly | JavaScript에서 쿠키 접근 불가능 (XSS 공격 방지) |
Secure | HTTPS에서만 쿠키 전송 가능 |
SameSite | CSRF 공격 방지 (Strict, Lax, None) |
Expires / Max-Age | 쿠키의 유효기간 설정 |
개발환경
크롬 브라우저
- console : 한줄의 javascript를 바로 동작시킬 수 있는 화면
- 멀티라인인스트럭션 : shift + enter
- source - network - arrow click - snippet - new snippet : javascript 파일을 생성하고 Run 시킬 수 있다.
HTML에서 JavaScript를 사용하는 방식
- 인라인 스크립트 (Inline Script) :
- <button onclick="alert('Hello, World!')">클릭하세요</button>
- 내부 스크립트 (Internal Script)
- <head> <meta charset="UTF-8"> <title>내부 스크립트</title> <script> function showMessage() { alert("안녕하세요!"); } </script> </head>
- 외부 스크립트 (External Script)
- JavaScript 코드를 별도의 .js 파일로 작성하고, <script src="파일경로"></script>로 불러오는 방식.
- CSS와는 달리 <script> 태그의 위치는 <body>의 뒤, 마지막에 위치한다. 이유는, 변경의 대상이 아직 DOM에 입력되지 않으면 null excpetion 문제가 발생하기 때문임.
JavaScript 문법
- html의 inline javascript로 사용되는 경우 String은 ''으로 표기한다
- 한줄의 끝에는 ;를 첨가한다
JavaScript Tag
예제코드 :
- <input type="button" value="night" onclick="document.querySelctor('body').style.backgroundColor='black';
document.querySelctor('body').style.color='white';">
- <input type="button" value="day" onclick="document.querySelctor('body').style.backgroundColor='white';
document.querySelctor('body').style.color='black';">
-
<input> : 사용자의 입력을 받기위한 개체를 입력하며, 속성값인 type에 따라 다양한 모습을 띈다
- onClickOrOtherAction = "액션에 따라서 동작을 시킬 JavaScriptCode", 이벤트 리스너로 html 속성값으로 약 20개 정도의 이벤트가 정의되어있음.
<script> : 동작시킬 JavaScript Code를 입력하는 html태그
Navigator
function as parameter
fetch then catch
Document Object Style Property
document.querySelctor(선택자) : 해당 문서에서 특정 선택자에 접근한다.
document.body.style.backgroundColor = "red"
document.body.style.color = "white"
Navigator Object Method and Property
Used when interacting with the browser's capabilities related to the client at runtime. The navigator object contains information about the browser and the operating system, and it offers methods to perform tasks like detecting the user's location and managing the connection status.
Methods of the navigator Object:
- geolocation: This attribute returns a Geolocation object that can be used to obtain the position of the device. It's not a method by itself but an object with its own methods.
- getCurrentPosition(success, error, options): Calls the success callback with the current position as soon as it's available. Optional error callback can be provided for handling any errors, and options can modify the behavior of the location retrieval.
- watchPosition(success, error, options): Similar to getCurrentPosition but calls the success callback every time the location changes.
- clearWatch(id): Stops watching the position by clearing the watch set up by watchPosition.
Console Object?
The console object provides access to the browser's debugging console. It is part of the Web APIs provided by browsers and is primarily used for debugging purposes. The console offers a variety of functions that developers can use to log information, errors, warnings, and more, helping them to debug and test their web applications directly within the browser.
- console.error() : Outputs an error message to the console. This typically displays the message with a red icon and text, making it easily distinguishable in the console output.
- console.log() : Logs general information to the console. It's the most frequently used method to display simple messages or variables' values during development.
HTTP Request : AJAX CODE
document.getElementById('submitButton').addEventListener('click', function() {
var userData = document.getElementById('inputData').value; // Get the user input
fetch('/processInput', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data: userData }) // Send the data as JSON
})
.then(response => response.json()) // Parse the JSON response
.then(data => {
document.getElementById('responseArea').innerText = data.message; // Display the response
})
.catch(error => console.error('Error:', error));
});
Fetch API
- fetch : The fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It returns a Promise that resolves to the Response to that request, whether it is successful or not.
- Fetch Function: This function initiates an HTTP request to the server at the endpoint /processInput.
- Method, Headers, and Body: The method specifies what type of HTTP method to use (e.g., POST, GET). The headers provide additional information needed for the request like content type. The body includes the data sent to the server, formatted as a JSON string.
- Handling Responses: The .then() and .catch() methods handle the response and errors, respectively. They ensure that once the server processes the request and sends back a response, it's appropriately managed in your JavaScript application.
- if the response is html text, ".then(response => response.text())" 을 통해서 body를 parsing해서 html로만들고,
- ".then(html => { document.getElementById('location').innerHTML = html;" innerhtml이라는 attribute을 통해서 html 중에서 contents를 바꾸고자하는 html을 부분적으로 업데이트 할 수 있다는 것.
- response has got json method that parse the response's body into json data type.
- Fetch Function: This function initiates an HTTP request to the server at the endpoint /processInput.
- Json Object
- JSON is treated as a global object that provides methods for parsing JSON content into JavaScript objects and converting JavaScript objects into JSON format.
- Method
- JSON.parse(): Converts a JSON string into a JavaScript object JSON.x`
- JSON.stringify(): Converts a JavaScript JSON object into a JSON string
- Serialization: This process converts the JavaScript object into a string that can be transmitted over a network or stored in a file or database. & Formatting : check if the json are well formatted
- json.key = value : JSON Object of javascript are made easy to parse value of key using its attribute.
'개발기술 > 프론트엔드' 카테고리의 다른 글
자바스크립트 문법 (0) | 2025.04.07 |
---|---|
프론트엔드 환경설정 및 배포 (0) | 2025.03.24 |
백엔드 개발자와 프론트 엔드 이해도 (0) | 2025.02.12 |
Java, Javascript, Python 비교 (1) | 2025.01.14 |
톰캣 설치를 통한 JSP 사용법 (0) | 2024.07.01 |