개요 및 구문
Fetch
Fetch()는 Fetch API 내의 JavaScript 창 개체 메서드의 일부입니다. 내장되어 있으므로 사용자가 설치할 필요가 없습니다. Fetch()를 사용하면 추가 라이브러리를 설치하지 않고도 API에서 비동기적으로 데이터를 가져올 수 있습니다.
fetch(url)
.then((res) => {
// handle response
})
.catch((error) => {
// handle error
});
위의 코드는 간단한 fetch() get 요청입니다. fetch() 메서드에는 url이라는 하나의 필수 인수가 있습니다. url은 사용자가 데이터를 얻고 자하는 경로입니다. 그런 다음 fetch() 메서드는 응답 객체를 해결하거나 오류로 거부 할 수 있는 promise를 반환합니다.
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.catch((error) => console.log(error));
fetch() 메서드의 두 번째 인수는 옵션이며 선택 사항입니다. 사용자가 옵션을 전달하지 않을 경우 요청은 항상 가져 와서 주어진 URL에서 콘텐츠를 다운로드합니다.
앞서 언급했듯이 promise는 응답 객체를 반환하므로 사용자는 응답 본문을 가져 오기 위해 다른 메서드를 사용해야 합니다. 본문의 형식에 따라 사용자가 사용할 수 있는 몇 가지 방법이 있습니다.
가장 인기 있는 것은 response.json()입니다.
불행히도 내장 fetch() 함수는 Node.js에 없지만 node-fetch와 같은 polyfill이 있습니다. node-fetch와 브라우저 fetch() 사이에는 몇 가지 알려진 변형이 있습니다.
Axios
Axios는 Node, XMLHttpRequest 또는 브라우저에서 HTTP 요청을 만들기 위한 JavaScript 라이브러리입니다. 최신 라이브러리로서 Promise API를 기반으로 합니다.
Axios에는 CSFR (교차 사이트 요청 위조) 공격에 대한 보호와 같은 몇 가지 장점이 있습니다. Axios 라이브러리를 사용하려면 사용자가 CDN, npm, Yarn 또는 Bower를 사용하여 이를 설치하고 프로젝트로 가져와야 합니다.
axios.get(url)
.then((response) => console.log(response))
.catch((error) => console.log(error));
위의 코드는 get 메서드와 응답 및 오류에 대한 간단한 콜백입니다. 사용자가 구성 개체를 만들 때 여러 속성을 정의 할 수 있습니다.
가장 일반적인 것은 url, baseURL, params, auth, headers, responseType 및 data입니다.
응답으로 Axios는 응답 객체 또는 오류 객체로 해결할 약속을 반환합니다. 응답 개체에는 다음 값이 있습니다.
axios({
url: "http://api.com",
method: "POST",
header: {
"Content-Type": "application/json",
},
data: { name: "Sabesan", age: 25 },
});
사용자는 fetch()에서 두 가지 약속으로 작업해야 합니다. 사용자는 Axios에서 상용구를 피하고 더 깔끔하고 간결한 코드를 작성할 수 있습니다.
Axios는 data 속성을 사용하지만 fetch()는 body 속성을 사용하여 데이터를 처리합니다. fetch()의 데이터는 문자열화됩니다. fetch()에서는 URL이 인수로 전달되지만 Axios에서는 URL이 config 객체에 설정됩니다.
JSON
Fetch
fetch() 메서드를 사용하면 사용자는 응답 데이터에 대해 일종의 메서드를 사용해야 합니다. 사용자가 요청과 함께 본문을 보낼 때 사용자는 데이터를 문자열화 해야 합니다.
fetch('url')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));
위의 코드에서 응답과 함께 사용자는 response.json() 작업을 처리해야 합니다. fetch()에서 JSON 데이터를 처리 할 때 2 단계 프로세스가 있습니다.
사용자는 먼저 실제 요청을 한 다음 응답에서 .json() 메서드를 호출해야 합니다.
Axios
Axios에서 사용자는 요청에 데이터를 전달하거나 응답에서 데이터를 가져 오면 데이터가 자동으로 문자열화 됩니다. 따라서 다른 작업이 필요하지 않습니다.
axios.get('url')
.then((response)=>console.log(response))
.catch((error)=>console.log(error))
위의 예에서는 하나만 필요하다는 것을 알 수 있습니다.
데이터 자동 변환은 Axios에서 사용할 수 있는 좋은 기능입니다.
Error Handling
Fetch
fetch() 메서드에서 응답을 받을 때마다 상태가 성공인지 확인해야 합니다. 그렇지 않아도 응답을 받을 수 있기 때문입니다. fetch()의 경우 요청이 완료되지 않는 경우에만 프라미스가 해결되지 않습니다.
fetch('url')
.then((response)=>{
if(!response.ok){
throw Error (response.statusText);
}
return response.json();
})
.then((data)=>console.log(data))
.catch((error)=>console.log(error))
Fetch()는 네트워크 오류를 발생 시키지 않습니다. 따라서 fetch()로 작업 할 때는 항상 response.ok 속성을 확인해야 합니다. 이 오류 검사를 함수로 추출하여 더 쉽고 재사용 할 수 있습니다.
const checkError = response => {
if (!response.ok) throw Error(response.statusText);
return response.json();
};
fetch("url")
.then(checkError)
.then(data => console.log(data))
.catch(error => console.log("error", error));
Axios
Axios에서는 Axios가 네트워크 오류를 발생 시키기 때문에 오류 처리가 매우 쉽습니다. 404와 같은 잘못된 응답이 있을 경우 프라미스가 거부되고 오류가 반환됩니다.
따라서 오류를 잡아 내고 어떤 종류의 오류인지 확인할 수 있습니다.
axios.get('url')
.then((response)=> console.log(response))
.catch((error)=>{
if(error.response){
// When response status code is out of 2xxx range
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request){
//When no response was received after request was made
console.log(error.request);
} else {
// Error
console.log(error.message);
}
})
Download Progress
큰 자산을 로드 할 때 진행률 표시기는 인터넷 속도가 느린 사용자에게 매우 유용합니다. 이전에 구현 된 진행률 표시기에서. 개발자는 XMLHttpRequest.onprogress를 콜백 핸들러로 사용했습니다.
Fetch
fetch()에서 다운로드 진행률을 추적하려면 response.body 속성 중 하나인 ReadableStream 객체를 사용할 수 있습니다. 청크별로 바디 데이터 청크를 제공하며 시간에 소비되는 데이터의 양을 계산할 수 있습니다.
// original code: https://github.com/AnthumChris/fetch-progress-indicators
const element = document.getElementById('progress');
fetch('url')
.then(response => {
if (!response.ok) {
throw Error(response.status+' '+response.statusText)
}
// ensure ReadableStream is supported
if (!response.body) {
throw Error('ReadableStream not yet supported in this browser.')
}
// store the size of the entity-body, in bytes
const contentLength = response.headers.get('content-length');
// ensure contentLength is available
if (!contentLength) {
throw Error('Content-Length response header unavailable');
}
// parse the integer into a base-10 number
const total = parseInt(contentLength, 10);
let loaded = 0;
return new Response(
// create and return a readable stream
new ReadableStream({
start(controller) {
const reader = response.body.getReader();
read();
function read() {
reader.read().then(({done, value}) => {
if (done) {
controller.close();
return;
}
loaded += value.byteLength;
progress({loaded, total})
controller.enqueue(value);
read();
}).catch(error => {
console.error(error);
controller.error(error)
})
}
}
})
);
})
.then(response =>
// construct a blob from the data
response.blob()
)
.then(data => {
// insert the downloaded image into the page
document.getElementById('img').src = URL.createObjectURL(data);
})
.catch(error => {
console.error(error);
})
function progress({loaded, total}) {
element.innerHTML = Math.round(loaded/total*100)+'%';
}
위의 예는 ReadableStream을 사용하여 이미지를 다운로드하는 동안 사용자에게 즉각적인 피드백을 제공하는 방법을 보여줍니다.
Axios
Axios에서는 진행률 표시기 구현도 가능하며 설치 및 구현할 수 있는 준비된 모듈이 있기 때문에 훨씬 더 쉽습니다. Axios Progress Bar라고 합니다.
loadProgressBar();
function downloadFile(url) {
axios.get(url, {responseType: 'blob'})
.then(response => {
const reader = new window.FileReader();
reader.readAsDataURL(response.data);
reader.onload = () => {
document.getElementById('img').setAttribute('src', reader.result);
}
})
.catch(error => {
console.log(error)
});
}
Upload Progress
Fetch
fetch()에서는 업로드 진행 상황을 모니터링 할 수 없습니다.
Axios
Axios에서 업로드 진행 상황을 모니터링 할 수 있습니다. 동영상 또는 사진 업로드 용 애플리케이션을 개발하는 경우 이는 거래 중단 요인이 될 수 있습니다.
const config = {
onUploadProgress: event => console.log(event.loaded)
};
axios.put("/api", data, config);
HTTP Interception
차단은 애플리케이션에서 서버로 또는 그 반대로 HTTP 요청을 확인하거나 변경해야 할 때 중요 할 수 있습니다 (예 : 인증, 로깅 등).
Fetch
Fetch()는 기본적으로 HTTP 차단을 제공하지 않습니다. fetch() 메서드를 덮어 쓰고 요청을 보내는 동안 수행해야 하는 작업을 정의 할 수 있지만 코드가 더 많이 필요하고 Axios의 기능을 사용하는 것보다 더 복잡 할 수 있습니다.
다음 코드와 같이 전역 fetch() 메서드를 덮어 쓰고 자체 인터셉터를 정의 할 수 있습니다.
fetch = (originalFetch => {
return (...arguments) => {
const result = originalFetch.apply(this, arguments);
return result.then(console.log('Request was sent'));
};
})(fetch);
fetch('url')
.then(response => response.json())
.then(data => {
console.log(data)
});
Axios
Axios HTTP 차단은 이 라이브러리의 주요 기능 중 하나입니다. 따라서 이를 사용하기 위해 추가 코드를 만들 필요가 없습니다.
// request interceptors
axios.interceptors.request.use((config)=>{
console.log('Request was sent');
return config;
})
// response interceptors
axios.interceptors.response.use((response) => {
// do an operation on response
return response;
})
axios.get('url')
.then((response)=>console.log(response))
.catch((error)=>console.log(error))
위 코드에서 axios.interceptors.request.use() 및 axios.interceptors.response.use() 메서드는 HTTP 요청이 전송되기 전에 실행할 코드를 정의하는 데 사용됩니다.
Response Timeout
Fetch
Fetch()는 AbortController 인터페이스를 통해 응답 시간 제한 기능을 제공합니다.
const controller = new AbortController();
const signal = controller.signal;
const options = {
method: 'POST',
signal: signal,
body: JSON.stringify({
firstName: 'Sabesan',
lastName: 'Sathananthan'
})
};
const promise = fetch('/login', options);
const timeoutId = setTimeout(() => controller.abort(), 5000);
promise
.then(response => {/* handle the response */})
.catch(error => console.error('timeout exceeded'));
위 코드에서 AbortController.AbortController() 생성자를 사용하여 AbortController 객체를 만들어야 합니다. AbortController 개체를 사용하면 나중에 요청을 중단 할 수 있습니다.
이전 기사 인 "JavaScript의 Fetch API에 대한 깊은 통찰력"에서 언급했듯이 신호가 읽기 전용 인 AbortController의 속성 인 방법에 대해 논의했습니다. 신호는 요청과 통신하거나 요청을 중단하는 방법을 제공합니다.
서버가 5 초 이내에 응답하지 않으면 controller.abort()를 호출하여 작업이 종료됩니다.
Axios
config 개체에서 선택적 timeout 속성을 사용하여 요청이 종료되기 전의 시간 (밀리 초)을 설정할 수 있습니다.
axios({
method: 'post',
url: '/login',
timeout: 5000, // 5 seconds timeout
data: {
firstName: 'Sabesan',
lastName: 'Sathananthan'
}
})
.then(response => {/* handle the response */})
.catch(error => console.error('timeout exceeded'))
JavaScript 개발자가 fetch() 대신 Axios를 선택하는 이유 중 하나는 시간 제한을 쉽게 설정할 수 있기 때문입니다.
Concurrent Requests
Fetch
여러 개의 동시 요청을 하려면 기본 제공 Promise.all() 메서드를 사용할 수 있습니다. fetch() 요청의 배열을 Promise.all()에 전달한 다음 응답을 처리하는 비동기 함수를 전달하기 만하면 됩니다.
Promise.all([
fetch('https://api.github.com/users/sabesansathananthan'),
fetch('https://api.github.com/users/rcvaram')
])
.then(async([res1, res2]) => {
const a = await res1.json();
const b = await res2.json();
console.log(a.login + ' has ' + a.public_repos + ' public repos on GitHub');
console.log(b.login + ' has ' + b.public_repos + ' public repos on GitHub');
})
.catch(error => {
console.log(error);
});
Axios
Axios에서 제공하는 axios.all() 메서드를 사용하면 위의 결과를 얻을 수 있습니다. 모든 가져 오기 요청을 배열로 axios.all() 메서드에 전달합니다. 다음과 같이 axios.spread() 함수를 사용하여 별도의 변수에 응답 배열의 속성을 할당합니다.
axios.all([
axios.get('https://api.github.com/users/sabesansathananthan'),
axios.get('https://api.github.com/users/rcvaram')
])
.then(axios.spread((obj1, obj2) => {
// Both requests are now complete
console.log(obj1.data.login + ' has ' + obj1.data.public_repos + ' public repos on GitHub');
console.log(obj2.data.login + ' has ' + obj2.data.public_repos + ' public repos on GitHub');
}));
Backward-Compatibility
이전 버전과의 호환성을 브라우저 지원이라고도 합니다.
Fetch
Fetch()는 Chrome 42+, Safari 10.1+, Firefox 39+ 및 Edge 14+ 만 지원합니다.
전체 호환 테이블은“Can I Use?”에서 확인할 수 있습니다 Fetch()를 지원하지 않는 웹 브라우저에서 fetch()와 유사한 기능을 구현하려면 windows.fetch()와 같은 폴리 필과 함께 fetch()를 사용할 수 있습니다.
fetch polyfill을 사용하려면 다음 npm 명령을 통해 설치하십시오.
npm install whatwg-fetch --save
어떤 이유로 든 polyfill 구현에 액세스해야 하는 경우 내보내기를 통해 사용할 수 있습니다.
import {fetch as fetchPolyfill} from 'whatwg-fetch'
window.fetch(...) // use native browser version
fetchPolyfill(...) // use polyfill implementation
일부 오래된 브라우저에서는 promise polyfill이 필요할 수도 있습니다.
Axios
Axios는 fetch()와 다릅니다. Axios는 광범위한 브라우저 지원을 제공합니다. IE11과 같은 오래된 브라우저도 문제없이 Axios를 실행할 수 있습니다. 전체 호환성 표는 Axios의 문서를 통해 확인할 수 있습니다.
결론
대부분의 HTTP 통신 요구에 대해 Axios는 사용하기 쉬운 API를 컴팩트 패키지로 제공합니다.
window.fetch를 기반으로 하는 작고 우아한 HTTP 클라이언트 인 ky와 같은 HTTP 통신을 위한 대체 라이브러리가 있습니다. XMLHttpRequest를 기반으로 하는 작은 점진적 클라이언트 측 HTTP 요청 라이브러리인 superagent.
그러나 Axios는 HTTP 요청이 많은 애플리케이션과 좋은 오류 처리 또는 HTTP 차단이 필요한 애플리케이션에 더 나은 솔루션입니다.
간단한 API 호출이 몇 개만있는 소규모 프로젝트의 경우 fetch ()가 좋은 솔루션이 될 수 있습니다.
https://betterprogramming.pub/why-javascript-developers-should-prefer-axios-over-fetch-294b28a96e2c
등록된 댓글이 없습니다.