Last updated: Mar 2, 2024
Reading time·3 min
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).ReferenceError: XMLHttpRequest is not defined
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, however, it's not included as a native module in Node.js (on the server).
To solve the "ReferenceError: XMLHttpRequest is not defined" error, install an
alternative package like node-fetch
or axios
, which are more recent and more
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.
Note that fetch
has been added in Node.js version 21, so if you use a more
recent version, you can remove the node-fetch
import and your code will still
work.
// Works in Node.js version 21 or more recent ✅ 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());
You can only use this approach if your Node.js version is 21 or more recent.
You can check your Node.js version by issuing the node -v
command in your
terminal.
node -v
axios
moduleAlternatively, you can use the popular axios module to make an HTTP request.
The axios
package is also universal and can be used on the browser and the
server.
First, install the module by running the following command.
npm install axios
Now you are able to import and use axios
.
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 as 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 by running the following command.
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 more verbose and much harder to read than
fetch
and axios
.
To solve the "XMLHttpRequest is not defined" error, install an alternative
package like node-fetch
or axios
, which are more recent and more
user-friendly ways to interact with a server.
If you need an XMLHttpRequest
replacement that works in Node.js, use the
xhr2
package.