JavaScript 修复 XMLHttpRequest is not defined 错误
出现“XMLHttpRequest is not defined”错误有两个主要原因:
- 尝试在 Node.js 应用程序(在服务器端)中使用 XMLHttpRequest。
- 拼写错误的 XMLHttpRequest 关键字(区分大小写)。
首先,检查 XMLHttpRequest 单词的拼写,有很多地方可能会出现拼写错误。
创建 XMLHttpRequests 的 XMLHttpRequest()
构造函数是一个内置在浏览器中的对象,它不作为 Node.js(在服务器上)中的内置模块包含在内。
要解决“XMLHttpRequest is not defined”错误,请安装替代包,如 node-fetch
或 axios
,它们是与服务器交互的更新且用户友好的方式。 如果大家需要在 Node.js 中工作的 XMLHttpRequest 替换,请使用 xhr2
包。
本文包含有关如何在 Node.js 应用程序中使用 node-fetch、axios 和 xhr2 模块的示例。
这是一个使用 node-fetch 模块的示例。
首先安装模块:
$ npm install node-fetch
现在我们可以在 Node.js 代码中使用该模块:
import fetch from 'node-fetch';
async function getUser() {
try {
const response = await fetch('https://www.jiyik.com/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());
请注意,在撰写本文时,要在 NodeJs 项目中使用 ES6 模块导入和导出,我们必须在 package.json 文件中将 type 属性设置为 module:
{
"type": "module",
// ... ?️ rest
}
浏览器也支持 fetch
方法,因此我们的客户端和服务器端代码将保持一致。
或者,可以使用流行的 axios
模块发出 HTTP 请求。
axios 包也是通用的,可以在浏览器和服务器上使用。
首先,安装模块:
$ npm install axios
现在我们可以使用它了:
import axios from 'axios';
async function getUser() {
try {
const response = await axios.get('https://www.jiyik.com/api/');
return response.data;
} catch (err) {
console.log(err);
}
}
console.log(await getUser());
axios 包非常好,因为它删除了 fetch()
方法附带的一些样板。 这是一个更高级别的抽象,允许我们编写更少的代码。
最后,如果我们需要在 Node.js 中工作的 XMLHttpRequest 替代方案,请使用 xhr2
包。
首先安装模块:
$ npm install xhr2
并在我们的 Node.js 代码中使用它:
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://www.jiyik.com/api/', true);
xhttp.send();
}
getUser();
XMLHttpRequest 方法比 fetch 或 axios 更冗长且更难阅读。