Why is $.ajax undefined when using jQuery on Node.js?

夙愿已清 提交于 2021-02-10 08:02:01

问题


I have a module that is supposed to run on the client, but I'm testing it on Node.js, so I'd like to make $.ajax to work.

I installed jQuery on the project:

$ npm install jQuery

Then I'm doing this:

var $ = require("jquery");
console.log($.ajax); // undefined

$.ajax is undefined.

It makes a bit of sense for me because ajax is static and I think the result of require("jquery") would be the equivalent of $.fn in the browser.

How do I use $.ajax on node?


回答1:


You can find the reason from this docs: 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.

But the setup code of the docs is out of date.

The latest setup code is:

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 = $;

Run this code, got:

$.get: function
$.ajax: function
normal

The normal text is the response from my local http server.

Dependencies versions:

"jsdom": "^15.2.1",
"jquery": "^3.4.1",


来源:https://stackoverflow.com/questions/29191339/why-is-ajax-undefined-when-using-jquery-on-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!