Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

우당탕탕 개발일지

Fetch 본문

Front-end/JavaScript

Fetch

YUDENG 2023. 5. 20. 21:49

fetch 함수에는 HTTP 요청을 전송할 URL과 HTTP 요청 메서드, HTTP 요청 헤더, 페이로드 등을 설정한 객체를 전달한다.

const promise = fetch(url [, options])

 

fetch 함수는 HTTP 응답을 나타내는 Response 객체를 래핑한 Promise 객체를 반환한다. 후속 처리 메서드 then을 통해 Promise가 resolve한 Response 객체를 전달받을 수 있다.

fetch('https://api.example.com/data')
	.then(response => {
    	console.log(response)
    });
    .catch(error => {
    	console.log(error);
    });

 

- HTTP 응답 처리

Response 객체는 HTTP 응답을 나타내는 다양한 프로퍼티를 제공한다.

 

  • status: HTTP 상태 코드 (예: 200, 404)
  • statusText: HTTP 상태 메시지 (예: "OK", "Not Found")
  • ok: 응답이 성공적인지 여부를 나타내는 불리언 값 (true 또는 false)
  • headers: 응답 헤더 정보를 담고 있는 Headers 객체
  • json(): JSON 형식의 데이터를 추출하여 Promise를 반환하는 메서드
  • text(): 응답 데이터를 텍스트 형식으로 추출하여 Promise를 반환하는 메서드

fetch 함수가 반환하는 Promise는 기본적으로 404 Not Found나 500 Internal Server Error와 같은 HTTP에러가 발생해도 에러를 reject하지 않고 불리언 타입의 ok 상태를 false로 설정한 Response 객체를 resolve한다. 오프라인 등의 네트워크 장애나 CORS 에러에 의해 요청이 완료되지 못한 경우에만 Promise를 reject 한다. 

 

따라서 fetch 함수가 반환한 Promise가 resolve한 불리언 타입의 ok 상태를 확인해 명시적으로 에러를 처리할 필요가 있다.

const wrongUrl = 'https://api.example.com/data';

fetch(wrongUrl)
	.then(response => {
    	if(!response.ok) throw new Error(response.statusText);
        return response.json();
    })

 

- HTTP 요청 전송

const url = 'https://api.example.com/data';

const request = {
	get(url) {
    	return fetch(url);
    },
    post(url, payload){
		return fetch(url, {
  			method: 'POST',
  			headers: {'Content-Type': 'application/json'},
  			body: JSON.stringify(payload)
	});
};

- GET 요청

request.get(Url)
	.then(response => {
    	if(!response.ok) throw new Error(response.statusText);
        return response.json();
    })
    .then(datas => console.log(data))
    .catch(err => console.error(err));

- POST 요청

request.post(Url, {
    userId: 1,
    title: 'JavaScript',
    completed: false
}).then(reponse => {
	if(!response.ok) throw new Error(response.statusText);
    return response.json();
    })
    .then(datas => console.log(datas))
    .catch(err => console.error(err));
728x90

'Front-end > JavaScript' 카테고리의 다른 글

비동기 프로그래밍  (0) 2023.05.16
DOM & EVENT (코딩앙마)  (0) 2023.04.27
To-Do List 만들기 3차  (0) 2023.04.11
To-Do List 만들기 2차  (0) 2023.04.06
To-Do List 만들기 1차  (0) 2023.04.03