2

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?

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • It `var $ = require("jQuery");` not `var $ = require("jquery");` – Tamil Selvan C Mar 22 '15 at 05:53
  • 1
    `$.ajax()` in a browser uses the XMLHttpRequest object in the browser to do its networking. That object does not exist in node.js so unless some sort of node-specific support for `$.ajax()` was installed, it wouldn't be there. – jfriend00 Mar 22 '15 at 07:44
  • why would you use jQuery on node? – epascarello Nov 20 '19 at 13:37
  • There is no ajax method in jquery package for nodejs. [For more info](https://stackoverflow.com/questions/27184300/why-is-there-no-ajax-method-in-jquery-package-for-node-js) – hbamithkumara Nov 20 '19 at 13:45

1 Answers1

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",
Lin Du
  • 88,126
  • 95
  • 281
  • 483