2025-01-26T02:57:06

This commit is contained in:
2025-01-26 02:57:06 +09:00
parent f867e689aa
commit a74d9fcb68
6 changed files with 186 additions and 1 deletions

View File

@@ -18,6 +18,12 @@ fetch는 네트워크 요청을 보내고 응답을 처리하기 위한 최신 J
* JSON 및 텍스트 처리 간편 : 응답 데이터를 간편하게 JSON으로 변환 가능.
* 더 직관적이고 간결한 문법 : 코드 가독성이 높음.
```javascript
fetch(url, options)
```
* url: 요청을 보낼 URL을 지정합니다.
* options (선택 사항): 요청에 대한 추가적인 설정을 지정할 수 있는 객체입니다. 예를 들어, method, headers, body 등을 설정할 수 있습니다.
### GET 요청
```javascript
fetch("https://api.example.com/data")
@@ -30,6 +36,9 @@ fetch("https://api.example.com/data")
.then((data) => console.log(data)) // 데이터 처리
.catch((error) => console.error("Fetch error:", error));
```
* then(): Promise 객체가 성공적으로 처리되었을 때 실행될 함수를 지정합니다.
* catch(): Promise가 실패했을 때 실행될 함수를 지정합니다.
### POST 요청
```javascript
fetch("https://api.example.com/data", {
@@ -44,6 +53,72 @@ fetch("https://api.example.com/data", {
.catch((error) => console.error("Fetch error:", error));
```
### Response 객체
Fetch API를 통해 네트워크 요청을 보내면, 서버에서 받은 응답은 Response 객체라는 형태로 제공됩니다. Response 객체는 HTTP 요청에 대한 메타데이터(예: 상태 코드, 헤더 등)와 응답 본문을 담고 있습니다.
#### 주요 속성
* ok: Boolean 값으로, 응답이 성공적이면 true, 실패하면 false를 반환합니다. (200-299 상태 코드 범위)
* status: HTTP 상태 코드를 나타냅니다. (예: 200, 404, 500)
* statusText: 상태 코드에 대한 텍스트 설명입니다. (예: "OK", "Not Found")
* headers: 응답 헤더를 나타내는 Headers 객체입니다.
* url: 응답을 받은 URL입니다.
* body: 응답 본문을 나타내는 ReadableStream입니다.
#### 주요 메서드
* json(): 응답 본문을 JSON 객체로 파싱하여 Promise를 반환합니다.
* text(): 응답 본문을 문자열로 변환하여 Promise를 반환합니다.
* blob(): 응답 본문을 Blob 객체로 변환하여 Promise를 반환합니다.
* arrayBuffer(): 응답 본문을 ArrayBuffer 객체로 변환하여 Promise를 반환합니다.
* formData(): 응답 본문을 FormData 객체로 변환하여 Promise를 반환합니다.
* clone(): Response 객체를 복사합니다.
#### Response 객체 활용 시 주의사항
* 응답 상태 확인: ok 속성과 status 속성을 확인하여 응답이 성공적인지 확인해야 합니다.
* 응답 형식 파악: 서버에서 보낸 응답의 Content-Type 헤더를 확인하여 적절한 메서드(json(), text(), blob() 등)를 사용해야 합니다.
```javascript
const form = document.getElementById('myForm');
const fileInput = document.getElementById('fileInput');
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('https://your-server-endpoint', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text(); // 서버에서 보낸 응답을 텍스트로 파싱
})
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
});
```
#### async/await을 이용한 Fetch API 사용
```javascript
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
```
## XMLHttpRequest
XMLHttpRequest는 자바스크립트의 오래된 네트워크 요청 API입니다.
AJAX 기술의 핵심 요소로, 웹 애플리케이션에서 서버와 비동기적으로 데이터를 교환할 수 있게 해줍니다.