◼ Fetch 함수란 ??
JavaScript에서 네트워크 요청을 만들고 처리하기 위해 사용되는 메서드입니다. 일반적으로 웹 브라우저에서 사용되며, 서버로부터 데이터를 가져오거나 서버로 데이터를 보낼 때 주로 사용한다.
fetch 함수는 Promise를 반환하며, 네트워크 요청을 비동기적으로 처리한다.
JSON파일을 가져올때 사용되는 함수 중 하나다.
fetch(url,{옵션})
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
})
◼ then ~ catch
fetch에서 요청한 데이터가 성공했을 때 실행된다.
fetch(url,{옵션}) // HTTP 요청을 보내고
.then(response => {
// 여기서 response는 서버로부터 받은 응답을 나타냅니다.
// 응답을 JSON 형식으로 파싱하여 반환합니다.
return response.json();
})
.then(data => { // 파싱(response.json()) 반환한 값을 받는다
console.log(data);
})
.catch(error => {
// 에러가 발생한 경우 처리합니다.
console.error('Error:', error);
});
파싱(parsing)은 주어진 데이터를 해석하고 원하는 형식으로 변환하는 과정을 의미
◼ Fetch 옵션
fetch('url', {옵션}) => 옵션에 request 설정하여 요청을 보낸다.
request 설정은 head와 body로 나누어 있다. head에는 어떻게 요청할 것인지, body는 요청하는 실제 데이터가 들어가 네트워크에 전달이 된다.
head에서 사용하는 GET, POST, PUT, DELETE 요청방법은 예시를 적어보았다.
GET : 조회하기
fetch('https://aaaa/api/members') // 기본적으로 데이터를 가져옴
.then(() => {
fetch('https://learn.codeit.kr/api/members')
.then((response) => response.test())
.then((result) => {
const members = JSON.parse(result);
console.log(members);
});
});
POST : 새로 만들기
const newMember = {
name: 'tom',
email: 'aaa@gmail.com',
department: 'CEO',
};
fetch('https://aaaa/api/members', {
method: 'POST', // 추가 메소드
headers: { // 추가된 부분
'Content-Type': 'application/json', // HEAD: Content-Type추가
},
body: JSON.stringify(newMember) // stringify: JSON객체로 변환해주는 메소드
})
.then(() => {
fetch('https://learn.codeit.kr/api/members')
.then((response) => response.text())
.then((result) => {
const members = JSON.parse(result);
console.log(members);
});
});
PUT : 수정하기
const member = {
name: 'tom',
email: 'tom@gmail.com',
department: 'CEO',
};
fetch('https://aaaa/api/members', {
method: 'PUT', // 수정 메소드
body: JSON.stringify(member) // stringify: JSON객체로 변환해주는 메소드
})
.then(() => {
fetch('https://learn.codeit.kr/api/members')
.then((response) => response.text())
.then((result) => {
const members = JSON.parse(result);
console.log(members[members.length - 1]);
});
});
DELETE : 삭제하기 [json() 메소드]
fetch('https://aaaa/api/members/12', { // 12번째 있는 정보 삭제
method: 'DELETE', // 삭제 메소드 , body는 없어도 됨
})
.then(() => {
fetch('https://learn.codeit.kr/api/members')
.then((response) => response.json()) // json메소드는 바로 JS객체로 변환 해준다
.then((result) => {
// const members = JSON.parse(result); //response.json()하면 안해도 됨
console.log(members[members.length - 1]);
});
});
'[노트장] 적으며 정리해 보는 이론 > 웹개발기본' 카테고리의 다른 글
[웹개발기본] async / await문 (0) | 2024.03.12 |
---|---|
[웹개발기본] Promise (1) | 2024.03.12 |
[웹개발기본] HEAD Content-Type (0) | 2024.03.11 |
[웹개발기본] Request의 종류 (0) | 2024.03.11 |
[웹개발기본] 직렬화, 역직렬화 : 데이터를 다른 형식으로 (0) | 2024.03.11 |