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?

4
  • It var $ = require("jQuery"); not var $ = require("jquery"); Commented Mar 22, 2015 at 5: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. Commented Mar 22, 2015 at 7:44
  • why would you use jQuery on node? Commented Nov 20, 2019 at 13:37
  • There is no ajax method in jquery package for nodejs. For more info Commented Nov 20, 2019 at 13:45

1 Answer 1

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",
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.