2

I need to do an ajax call from node server using TypeScript. I am importing jquery as below to my class

import * as $ from "jquery"

if I hover over my implementation, it recognizes the ajax as below

enter image description here

Then, I compile this TypeScript to JavaScript. It is successful.

If I host the node server and try to access this function I am getting below error

TypeError : $.ajax is not a function.

I think I am missing something. I am unable to figure the things out.

1
  • 6
    Using jQuery from Node makes no sense. You should use a server-side HTTP client, such as Axios or Request. Commented Dec 14, 2017 at 15:00

1 Answer 1

2

Don't do this; jQuery is for the client side, not the server

As mentioned in comments, You should use a server-side HTTP client, such as the built in http.request method, or a library such as npm-fetch or Axios as your needs might dictate.


However, assuming you're using the jquery npm package, please note the following quote from the package page:

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.

What the npm package provides is a factory for instantiating jQuery injected with a faked window. They give an example of how to do that, but this part is pretty revealing:

This can be useful for testing purposes.

"For testing purposes" means purposes such as running unit tests in nodejs as part of your build pipeline for a client side package. Not as a general purpose library for use in node.

Sign up to request clarification or add additional context in comments.

1 Comment

...and if you do want to use jquery for HTML parsing and traversal in node, you're better off with cheerio, which has the same API as jquery, but a much faster DOMless implementation for the server.

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.