首页 > 解决方案 > 使用 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 现在我几乎被这个问题困住了,

谢谢,

标签: javascriptjquerynode.jsajaxhttp

解决方案


jQuery 被设计为在 Web 浏览器中运行,而不是在 Node.js 中运行。它确实不适合 Node.js。

请参阅文档,其中说:

要让 jQuery 在 Node 中工作,需要一个带有文档的窗口。由于 Node 中不存在这样的窗口,因此可以通过 jsdom 等工具来模拟。这对于测试目的很有用。

然后它给出了一个如何做到这一点的例子……但这个例子不起作用jsdom,因为它使用的特性已被弃用

如果您想在服务器端执行 Ajax,最好使用专为 Node.js 设计的库。Axios是一个受欢迎的选择。如果你想用它获取 HTML,然后用类似 jQuery 的 API 处理它,那么看看Cheerio


推荐阅读