JavaScript / Node.js で "ReferenceError: fetch is not defined" エラーが発生した場合の解決策
ブラウザまたは Node.js でコードを実行すると、ReferenceError: fetch is not defined
というエラーが発生する。
原因
fetch
はブラウザの API であり、Node.js 標準環境では利用できません。Node.js で fetch
を使用するには、node-fetch
などのライブラリをインストールする必要があります。
解決策
以下のいずれかの方法で解決できます。
ブラウザの場合
- コード内に
fetch
ポリフィルを追加する。 - CDN から
fetch
を読み込む。
Node.js の場合
node-fetch
ライブラリをインストールする。
詳細
ブラウザでは、fetch
は標準の API として提供されています。そのため、特別な設定なしでコード内で fetch
を使用できます。
しかし、古いブラウザでは fetch
がサポートされていない場合があります。その場合は、コード内に fetch
ポリフィルを追加する必要があります。
ポリフィルは、古いブラウザで fetch
を動作させるための JavaScript コードです。いくつかのポリフィルが公開されていますが、人気のあるものは次のとおりです:
これらのポリフィルは、CDN から読み込むこともできます。
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/fetch.umd.min.js"></script>
npm install node-fetch
ライブラリのインストール後、コード内で fetch
を使用できます。
const fetch = require('node-fetch');
fetch('https://example.com/')
.then(response => response.text())
.then(text => console.log(text));
ブラウザ
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch API サンプル</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/fetch.umd.min.js"></script>
<script>
fetch('https://example.com/')
.then(response => response.text())
.then(text => console.log(text));
</script>
</body>
</html>
Node.js
const fetch = require('node-fetch');
fetch('https://example.com/')
.then(response => response.text())
.then(text => console.log(text));
fetch を使用しない代替方法
XMLHttpRequest
は、ブラウザで古くから使用されている API です。fetch
よりも汎用性があり、複雑なリクエストにも対応できます。
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
};
xhr.send();
jQuery は、JavaScript のライブラリです。ajax
メソッドを使用して、簡単に HTTP リクエストを実行できます。
$.ajax({
url: 'https://example.com/',
success: function(data) {
console.log(data);
},
error: function(error) {
console.error(error);
}
});
Axios は、HTTP リクエストを行うための JavaScript ライブラリです。fetch
よりも使いやすく、多くの機能が備えています。
axios.get('https://example.com/')
.then(response => console.log(response.data))
.catch(error => console.error(error));
node-request
は、Node.js で HTTP リクエストを行うためのライブラリです。fetch
よりも多くの機能が備えられています。
const request = require('request');
request('https://example.com/', (error, response, body) => {
if (error) {
console.error(error);
} else {
console.log(body);
}
});
上記以外にも、さまざまな方法があります。
javascript node.js