はじめに
JavaScriptでHTTPリクエストを送るためによく使われるライブラリにaxios
がありますが、ここではaxios
以外の方法を紹介します。それらはfetch
APIとXMLHttpRequest
です。
Fetch APIを使う方法
fetch
はブラウザの組み込み機能であり、非常にシンプルなHTTPリクエストを送ることができます。以下に、fetch
を使用したGETリクエストの例を示します。
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
POSTリクエストも同様に送ることができます。
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({key: 'value'}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => console.error('Error:', error));
XMLHttpRequestを使う方法
XMLHttpRequest
はより古いブラウザでも対応しているHTTPリクエストを送るためのAPIです。以下に、XMLHttpRequest
を使用したGETリクエストの例を示します。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
}
xhr.send();
POSTリクエストも同様に送ることができます。
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
}
xhr.send(JSON.stringify({key: 'value'}));
まとめ
JavaScriptでHTTPリクエストを送るための方法は、axios
だけでなく、fetch
APIやXMLHttpRequest
など、複数の手段があります。使用する手段は、ブラウザの互換性、コードの可読性、必要な機能などにより選択します。それぞれの方法を理解し、適切に使い分けることが重要です。