8
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

Organization

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
8
Help us understand the problem. What are the problem?