Skip to content Skip to sidebar Skip to footer

Why Is $.ajax Undefined When Using Jquery On Node.js?

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 T

Solution 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",

Post a Comment for "Why Is $.ajax Undefined When Using Jquery On Node.js?"