JavaScript, TS

fetch API

개발하는지호 2023. 12. 10. 16:21

Ajax 프로그래밍 방식에서 주로 사용하던 API는 XMLHttpRequest였는데, 보다 간소화되어 사용이 조금 더 편리해진 API

 

무언가를 가져오다, 불러오다를 뜻하는 Fetch로 네이밍된 API이다.

 

기본 사용법

활용 예시

const detectLanguage = async (text) => {
let sourceLanguage;

const url = '/detectLangs';
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query: text }),
};

await fetch(url, options)
.then(response => response.json())
.then(data => {
sourceLanguage = data.langCode;
sourceSelect.value = sourceLanguage;
})
.catch(error => console.error(error));

return sourceLanguage;
}