자바스크립트 함수

Dear·2025년 4월 24일

TIL

목록 보기
13/74

예제 프로젝트를 만들면서 사용한 함수 정리

💙 fetch

자바스크립트에서 비동기적으로 HTTP 요청을 보낼 수 있는 브라우저 내장 함수

기본적으로 Promise를 반환하며, .then()과 .catch() 메서드를 통해 응답 처리와 오류 처리를 연결할 수 있다. 주로 서버에 데이터를 가지고오거나 보낼 때 사용한다.

// 기본 문법
fetch(url, options)
	.then(response => {
  		// 응답처리
	})	
	.catch(error => {
  		// 에러처리
	});

// GET 요청
fetch('https://api.example.com/data')
	.then(response => reponse.json()) // JSON으로 변환
	.then(data => console.log(data)) // 데이터 출력
	.catch(error => console.error('에러 발생 : ', error));

// POST 요청
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('에러 발생:', error));

💙 요소 생성 / 삽입 / 삭제

// 요소 생성 및 삽입
// Vanilla JS
const p = document.createElement('p');
p.textContent = '새로 추가된 요소';
document.body.appendChild(p);

// jQuery
const p = $('<p>새로 추가된 요소</p>');
$('body').append(p);

// 다른 위치에 삽입
// Vanilla JS
const parent = document.getElementById('container');
const newDiv = document.createElement('div');
newDiv.textContent = '중간 삽입';
parent.insertBefore(newDiv, parent.firstChild);

// jQuery
const newDiv = $('<div>중간 삽입</div>');
$('#container').prepend(newDiv);

// 요소 삭제
// Vanilla JS
const elem = document.getElementById('removeMe');
elem.remove();

// jQuery
$('#removeMe').remove();

🤍회고

오늘은 지금까지 배운 내용을 복습하면서 간단한 예제 프로젝트를 만들어보았다. 이를 통해 개념을 다시 정리하고 실습해보는 시간을 가졌다. fetch를 활용하면서 프론트엔드에서 데이터를 처리하는 방식에 사용하면서, 실제 백엔드 서버와 연동하여 데이터를 주고받는 경험도 해보고 싶다는 생각이 들었다.

profile
친애하는 개발자

0개의 댓글