Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

javascript - XMLHttpRequest module not defined/found

This is my code:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.open("GET", "//URL")
xhr.setRequestHeader("Content-Type: application/json", "Authorization: Basic //AuthKey");
xhr.send();

I am getting the error:

Cannot find module 'xmlhttprequest'

When I remove the first line, I am getting:

XMLHttpRequest is not defined

I have searched all over and people have mentioned a problem with Node.js here and there but my installation of Node was correct so I'm not sure what the issue is.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

XMLHttpRequest is a built-in object in web browsers.

It is not distributed with Node. The http module is the built-in tool for making HTTP requests from Node.

Most people making HTTP requests from node use a third party library with a friendlier API. Two popular choices are Axios (for use both in Node.js and browsers) and node-fetch (which implements the fetch API which is built into browsers and is a modern replacement for XMLhttpRequest.

If you really want to use XHR in Node.js then there are a couple of third party implementations. xmlhttprequest (which seems to be unmaintained) and xhr2 (which has had an update this year).

  1. Install it with npm,

     npm install xhr2
    
  2. Now you can require it in your code.

     var XMLHttpRequest = require('xhr2');
     var xhr = new XMLHttpRequest();
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...