目次
1. はじめに
JavaScript を使って HTTP(S)リクエストを送信するには、大きく分けると以下の 2つの方法が用意されています。
XMLHttpRequest は古くから存在している低レベルなオブジェクトであり、そのまま使うというよりは、何かしらラッパーとなるライブラリを使うことが多いです。
Fetch API は新しい仕様で、そのまま使ってもそれほど苦にならない程度には、XMLHttpRequest より使いやすくなっています。但し、使いやすく開発された XMLHttpRequest のラッパーライブラリと比べて使いやすいかと言えば、少し微妙です。一方、Fetch API のラッパーとなるライブラリには、まだ決定版と言えるものがないようです。
本ページでは、これらを踏まえて JavaScript による HTTP(S)リクエスト送信のコードをいくつか紹介します。
2. JSON を取得するコード
JSON を返すURLにアクセスするコードのサンプルを見ていきます。
※ XMLHttpRequest オブジェクトはそのまま使わず、ラッパーライブラリである axios を利用します。
(1) axios (XMLHttpRequest) (基本形)
axios を使うコードの基本形です。
response.data がそのまま JSON オブジェクトになっています。
GETメソッドの場合
axios.get('https://example.com/foo/')
.then(response => {
console.log(JSON.stringify(response.data));
})
.catch(error => {
console.error(error);
})
.finally(() => {
// skip
});
POSTメソッドの場合
axios.post('https://example.com/foo/', {
firstName: 'Ichiro',
lastName: 'Suzuki'
})
.then(response => {
console.log(JSON.stringify(response.data));
})
.catch(error => {
console.error(error);
})
.finally(() => {
// skip
});
(2) axios (XMLHttpRequest) (async/await を使用)
async/await を使ってみました。
分かりやすくするため、button要素の click イベントにイベントリスナーを登録する形にしています。
document.querySelector('#btn').addEventListener('click', async () => {
try {
const response = await axios.get('https://example.com/foo/');
console.log(JSON.stringify(response.data));
} catch (error) {
console.error(error);
}
});
(3) Fetch API (基本形)
Fetch API 用コードの基本形です。
fetch('https://example.com/foo/', {
method: "GET",
mode: "cors"
})
.then(response => {
if (response.ok) {
return response.json();
}
// 404 や 500 ステータスならここに到達する
throw new Error('Network response was not ok.');
})
.then(resJson => {
console.log(JSON.stringify(resJson));
})
.catch(error => {
// ネットワークエラーの場合はここに到達する
console.error(error);
})
response.okをチェックする必要があります。response.okが false の場合と、.catch()句内の2箇所にエラー処理が分かれています。
responseオブジェクトから JSON オブジェクトを取得する (response.json()) ために、Promiseチェーンが1段階増えます。fetch()の注意点については、Fetch を使う – Web API | MDN を参照してください。
(4) Fetch API (json().then() を使用)
fetch('https://example.com/foo/', {
method: "GET",
mode: 'cors'
})
.then((response) => {
if (response.ok) {
return response.json().then(resJson => {
console.log(JSON.stringify(resJson));
});
}
throw new Error('Network response was not ok.');
})
.catch(error => {
console.error(error);
})
- Promiseチェーンを1つ減らすために、
response.json()をreturnで返さず、.then()をつなげています。
(5) Fetch API (async/await を使用)
async/await を使ってみます。
分かりやすくするため、button要素の click イベントにイベントリスナーを登録する形にしています。
document.querySelector('#btn').addEventListener('click', async () => {
try {
const response = await fetch('https://example.com/foo/', {
method: "GET",
mode: 'cors'
});
if (response.ok) {
const resJson = await response.json();
console.log(JSON.stringify(resJson));
} else {
throw new Error('Network response was not ok.');
}
} catch (error) {
console.error(error);
}
});
- 非同期処理である
fetch()とresponse.json()に await をつけることで同期処理にし、その戻り値を変数にセットしています。
3. デモページ
以下のリンク先に、デモを用意しました。
デモページ
? JavaScript でHTTP(S)リクエストを送信する4. おわりに
個人的には、(2) が一番シンプルで分かりやすいと感じます。
fetch() メソッドは エラー処理がシンプルに書けないし、.json() メソッドが必要だったりして(しかも非同期!)ちょっと面倒です。使い勝手のよいラッパーライブラリの誕生が望まれます。





