LoginSignup
8
8

More than 5 years have passed since last update.

Node.jsでFetch APIを使うと XMLHttpRequest is not defined になる

Posted at

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-fetchnode-fetch などのラッパー実装が必要になる。

8
8
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
8
8