javascript - 使用 Node 执行 js 代码时出错:“$.ajax 不是函数”
问题描述
这是代码,我想创建 js 代码来请求有表单数据的 Web 服务并在控制台中打印这些数据我使用 Node.js 运行此代码:
//importing jQuery
var $ = require('jQuery');
//defining the parameters of HTTP request
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.kizeoforms.com/rest/v3/forms/",
"method": "GET",
"headers": {
"content-type": "application/json",
"Authorization": "perma_restv3_MTH_024b61f4bf72fd4c46d7633be7e21e083d8b660f",
"cache-control": "no-cache",
}
}
//sending request and printing of response in console
$.ajax(settings).done(function (response) {
console.log(response);
});
这是控制台发送给我的内容:
$.ajax(settings).done(function (response) {
^
TypeError: $.ajax is not a function
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
[Finished in 0.1s]
我已经安装了 jQuery 现在我几乎被这个问题困住了,
谢谢,
解决方案
jQuery 被设计为在 Web 浏览器中运行,而不是在 Node.js 中运行。它确实不适合 Node.js。
请参阅文档,其中说:
要让 jQuery 在 Node 中工作,需要一个带有文档的窗口。由于 Node 中不存在这样的窗口,因此可以通过 jsdom 等工具来模拟。这对于测试目的很有用。
然后它给出了一个如何做到这一点的例子……但这个例子不起作用jsdom
,因为它使用的特性已被弃用。
如果您想在服务器端执行 Ajax,最好使用专为 Node.js 设计的库。Axios是一个受欢迎的选择。如果你想用它获取 HTML,然后用类似 jQuery 的 API 处理它,那么看看Cheerio。
推荐阅读
- c - 如何在“问题”部分的 Vscode 上显示 C 中的错误代码
- amazon-web-services - 当 SSM 运行命令状态更改时终止 AWS EC2 实例
- wordpress - 如何在旋转滑块中移动图像而不移动接触形式
- javascript - 验证 Bootstrap 4 表单的两个复选框
- java - 是否建议在 java 中使用 PreparedStatement.setBoolean(1, Boolean.TRUE)?
- django-models - 如何解决这个问题,从 scrapy_djangoitem import DjangoItem ImportError: No module named scrapy_djangoitem
- django - 如何重新定义抽象模型中的属性?
- c# - 我如何将此编码器反转为解码器?
- python - 使用 HTML5 的角度拖放无法通过 Selenium 和 Python 工作
- python - 正确构建python PIP包