Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Fabian Blank
The "XMLHttpRequest is not defined" error occurs for 2 main reasons:
XMLHttpRequest
in a Node.js application (on the server
side).XMLHttpRequest
keyword (it's case sensitive).First and foremost, check the spelling of the XMLHttpRequest
word, there are
quite a few places where you could make a typo.
The XMLHttpRequest() constructor which creates XMLHttpRequests is an object that's built in in the browsers, it's not included as a native module in Node.js (on the server).
To solve the "XMLHttpRequest is not defined" error, install an alternative
package like node-fetch
or axios
, which are more recent and user friendly
ways to interact with a server. If you need an XMLHttpRequest
replacement that
works in Node.js, use the xhr2
package.
node-fetch
, axios
and xhr2
modules in your Node.js application.Here's an example that uses the node-fetch module.
First install the module:
npm install node-fetch
Now you can use the module in your Node.js code:
import fetch from 'node-fetch'; async function getUser() { try { const response = await fetch('https://randomuser.me/api/'); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } } console.log(await getUser());
Note that, at the time of writing, to use ES6 module imports and exports in a
NodeJs project, you have to set the type
property to module
in your
package.json
file:
{ "type": "module", // ... 👇️ rest }
The fetch
method is also supported in browsers, so your client and server side
code will be consistent.
Alternatively, you can use the popular axios module to make an HTTP request.
The axios
package is also universal, you can use it on both the browser and
the server.
First, install the module:
npm install axios
Now you are able to use it:
import axios from 'axios'; async function getUser() { try { const response = await axios.get('https://randomuser.me/api/'); return response.data; } catch (err) { console.log(err); } } console.log(await getUser());
The axios
package is quite nice in that it removes some of the boilerplate
that comes with the fetch()
method. It's a higher level abstraction that
allows us to write less code.
Finally, if you need an XMLHttpRequest
alternative that works in Node.js, use
the xhr2 package.
First install the module:
npm install xhr2
And use it in your Node.js code:
import XMLHttpRequest from 'xhr2'; function getUser() { const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function logger() { if (this.readyState === 4 && this.status === 200) { console.log(this.responseText); } }; xhttp.open('GET', 'https://randomuser.me/api/', true); xhttp.send(); } getUser();
The XMLHttpRequest
approach is quite more verbose and harder to read than
either fetch
or axios
.