You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js运行JS代码报错:TypeError: XMLHttpRequest is not a constructor

Why You're Getting "TypeError: XMLHttpRequest is not a constructor" in Node.js

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/https Modules
    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 like axios or node-fetch work seamlessly in both Node.js and browsers.
    Example with axios:

    1. Install first: npm install axios
    2. 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();
    
  • Replicate XMLHttpRequest with xhr2
    If you need to keep using the exact XHR syntax (maybe for code compatibility), the xhr2 package mimics the browser’s XMLHttpRequest in Node.js.

    1. Install it: npm install xhr2
    2. 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();
    

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:24:02