我有一个应该在客户端上运行的模块,但我正在 Node.js 上测试它,所以我想让 $.ajax
工作。
我在项目上安装了jQuery
:
$ npm install jQuery
然后我这样做:
var $ = require("jquery");
console.log($.ajax); // undefined
$.ajax
未定义。
这对我来说有点意义,因为 ajax
是静态的,我认为 require("jquery")
的结果等同于 $ .fn
在浏览器中。
如何在 Node 上使用 $.ajax
?
最佳答案
你可以从这个文档中找到原因:https://www.npmjs.com/package/jquery#node
For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as jsdom. This can be useful for testing purposes.
但是文档的设置代码已经过时了。
最新的设置代码是:
var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = new JSDOM("").window;
global.document = document;
var $ = require("jquery")(window);
// test
console.log("$.get:", typeof $.get);
console.log("$.ajax:", typeof $.ajax);
$.get("http://localhost:3000", data => {
console.log(data);
});
module.exports = $;
运行这段代码,得到:
$.get: function
$.ajax: function
normal
普通
文本是来 self 本地 http 服务器的响应。
依赖版本:
"jsdom": "^15.2.1",
"jquery": "^3.4.1",
关于javascript - 为什么在 Node.js 上使用 jQuery 时 $.ajax 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29191339/