LoginSignup
1
2

JavaScriptでaxios以外の方法 【HTTPリクエストを送る】

Posted at

はじめに

JavaScriptでHTTPリクエストを送るためによく使われるライブラリにaxiosがありますが、ここではaxios以外の方法を紹介します。それらはfetchAPIと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だけでなく、fetchAPIやXMLHttpRequestなど、複数の手段があります。使用する手段は、ブラウザの互換性、コードの可読性、必要な機能などにより選択します。それぞれの方法を理解し、適切に使い分けることが重要です。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2