问题
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