Node.js运行JS代码报错:TypeError: XMLHttpRequest is not a constructor
Hey Tony, let's break down this error you're running into—super common when moving browser code to Node.js!
The Core Issue
XMLHttpRequest is a browser-only API; it’s baked into web browsers to handle HTTP requests from the client side. Node.js, being a server-side runtime, doesn’t include this browser-specific tool by default. When you try to call new XMLHttpRequest() in your Node script, the runtime has no clue what that constructor is, hence the error.
Fixes to Try (Pick What Fits Your Project)
Here are three solid solutions depending on your needs:
Use Node.js’s Built-in
http/httpsModules
Node comes with native modules for handling HTTP/HTTPS requests out of the box—no extra installs needed. Here’s a quick GET request example:const https = require('https'); https.get('https://api.example.com/data', (res) => { let rawData = ''; res.on('data', (chunk) => { rawData += chunk; }); res.on('end', () => { try { const parsedData = JSON.parse(rawData); console.log(parsedData); } catch (err) { console.error('Error parsing data:', err.message); } }); }).on('error', (err) => { console.error('Request failed:', err.message); });Opt for a Third-Party HTTP Library
For cleaner syntax (especially for POST/PUT requests or JSON handling), libraries likeaxiosornode-fetchwork seamlessly in both Node.js and browsers.
Example withaxios:- Install first:
npm install axios - Then use it in your code:
const axios = require('axios'); async function fetchData() { try { const response = await axios.get('https://api.example.com/data'); console.log(response.data); } catch (error) { console.error('Request error:', error.message); } } fetchData();- Install first:
Replicate
XMLHttpRequestwithxhr2
If you need to keep using the exact XHR syntax (maybe for code compatibility), thexhr2package mimics the browser’sXMLHttpRequestin Node.js.- Install it:
npm install xhr2 - Update your script:
const XMLHttpRequest = require('xhr2'); const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/data'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { console.log(JSON.parse(xhr.responseText)); } else { console.error('Request failed with status:', xhr.status); } }; xhr.onerror = function() { console.error('Network error occurred'); }; xhr.send();- Install it:
Choose the approach that aligns with your project’s goals—native modules for zero dependencies, third-party libraries for simplicity, or xhr2 if you need to stick to XHR-style code.
内容的提问来源于stack exchange,提问作者Tony

