Node.js で Fetch API を使う際、とりあえず whatwg-fetch
を使って以下のようなコードを書いてみると Error: XMLHttpRequest is not defined
というエラーが出る
const { fetch } = require("whatwg-fetch");
fetch('https://httpstat.us/200')
.catch(e => console.log(e)) // Error: XMLHttpRequest is not defined
.then(r => console.log(r));
解決策
結論から言うと、Node.js では isomorphic-fetch
を使うのが正しい。
const fetch = require("isomorphic-fetch")
fetch('https://httpstat.us/200')
.catch(e => console.log(e))
.then(r => console.log(r)); // Response {}
XMLHttpRequest
は基本的にはブラウザ固有のAPIになっている。Node.js にはこの代替として Http API が用意されているので、ブラウザと互換な Fetch API を使うにあたっては今回の記事のように isormorphic-fetch
や node-fetch
などのラッパー実装が必要になる。