fetch함수를 사용하여 데이터를 비동기로 요청할 수 있다.
AJAX
(Asynchronous JavaSctipt And XML, 비동기적 자바스크립트와 XML)
비동기 HTTP 요청 기술을 나타내는 용어
JSONplaceholder
https://jsonplaceholder.typicode.com/
예제에서는 Fake REST API를 사용한다.
fetch함수의 기본은 GET으로 간단하게 사용할 수 있다.
- 첫번째
then: 요청이 성공할 경우response객체를 받아json형태로 파싱- 두번째
then:json형태의 응답body의 데이터를 출력catch: 요청이 완료되지 못할 때 에러 처리
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log('Fetch err', err));
await async와 함께 사용async function getUsers() {
let res = await fetch('https://jsonplaceholder.typicode.com/users');
let data = await res.json();
console.log(data);
}
header내용을 추출할 수 있다.for (let [key, value] of res.headers) {
console.log(`${key} = ${value}`);
}
POST의 경우 fetch함수의 두번째 인자에 method와 body정보를 넘겨야 한다.
headers:json을 전송하기 때문에Content-Type을application/json으로 설정한다.body:JSON.stringify()함수를 사용하여json형태로 전달한다.
fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
body: JSON.stringify({
name: 'foo',
username: 'bar',
}),
})
.then(res => res.json())
.then(data => console.log(data))
await async와 함께 사용async function getUsers() {
let res = await fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
body: JSON.stringify({
name: 'foo',
username: 'bar',
}),
});
let data = await res.json();
console.log(data);
}
fetch('https://jsonplaceholder.typicode.com/users', {
method: 'PUT,
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
body: JSON.stringify({
name: 'foo',
username: 'bar',
}),
})
.then(res => res.json())
.then(data => console.log(data))
fetch함수를 호출하면 브라우저는 요청을 보내고 promise객체를 반환한다.promise가 resolved되어 response객체가 반환된다. response객체는 ok, status프로퍼티를 이용하여 응답 성공 여부를 확인할 수 있다. http요청이 완료되지 못한 상태라면 promise가 rejected된다. 이 경우 catch함수를 사용하여 에러를 처리한다.fetch의 기본 문법url: 접근하고자 하는 urloptions: 선택 매개변수, method나 header 등을 지정fetch(url, [options])
.then(response => response.json())
.then(result => /* result 출력 */);
// ES5
fetch(url, [options])
.then(function(response) {
return response.json();
})
.then(function(result) {
return /* result 출력 */
});
await async를 함께 사용할 경우에는async function getResult() {
let response = await fetch(url, [options]);
let result = await response.json();
/* result 출력 */
};
response객체의 프로퍼티
-response.status:http상태 코드
-response.ok: 응답 상태가200~299일 경우true
-response.headers:http헤더fetch의 옵션
-method:http메서드
-headers: 요청 헤드가 담긴 객체
-body: 보내려는 데이터(요청 본문)
https://jsonplaceholder.typicode.com/
https://hogni.tistory.com/142
https://yeri-kim.github.io/posts/fetch/
https://ko.javascript.info/fetch