[英]Error executing js code with Node : "$.ajax is not a function"
这是代码,我想创建 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 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.