这是代码,我想创建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,现在我几乎已经陷入了这个问题,
谢谢
答案 0 :(得分:1)
jQuery旨在在Web浏览器中运行,而不是在Node.js中运行。确实不适合Node.js。
请参见the documentation,其中指出:
要使jQuery在Node中工作,需要一个带有文档的窗口。由于Node本身不存在这样的窗口,因此可以通过jsdom之类的工具来模拟。这对于进行测试很有用。
然后给出一个示例,说明如何执行此操作……但是示例不起作用,因为它使用are deprecated的jsdom
的功能。
如果要在服务器端执行Ajax,最好使用旨在在Node.js上运行的库。 Axios是一个受欢迎的选择。如果要使用它获取HTML,然后使用类似jQuery的API对其进行处理,请查看Cheerio。