0

I use node.js, Firebase Functions. I try to implement a very simple function (in functions/index.js) that use POST method to get response from third party website:

exports.haveData = functions.https.onCall((data, context) => {

    var $ = require('jquery');
    $.ajax(
        {
            type: 'post',
            url: 'http://example.com/info.html',
            data: {
                "id": data.id
            },
            success: function (response) {
                console.log("Success !!");
            },
            error: function () {
                console.log("Error !!");
            }
        }
    );

    return "Function ended";
});

But I have error code:

Unhandled error TypeError: $.ajax is not a function
    at /workspace/index.js:35:7
    at func (/workspace/node_modules/firebase-functions/lib/providers/https.js:273:32)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) 

I cannot figure out what can be the problem... :(

3
  • 2
    There are many other better libraries than jquery that can be used for making HTTP requests in nodejs. Commented Nov 2, 2020 at 21:37
  • If you want to do http request in node use either api provided directly by node http or https or use a module like axios Commented Nov 2, 2020 at 21:45
  • Does this answer your question? Why is $.ajax undefined when using jQuery on Node.js? Commented Nov 2, 2020 at 21:46

2 Answers 2

1

jQuery is not ideally suited for Node.js as the former independently wraps and/or applies properties to browser objects, like window and document. jQuery's ajax, for example, takes advantage of window.XMLHttpRequest.

In order to handle this natively you will need to either take advantage of Node's http package (using its request method) or install an NPM package that simplifies it for you. I would recommend axios as its API can be used by a browser or Node but there many competent options to choose from.

Node's HTTP: https://nodejs.org/api/http.html

Axios JS: https://www.npmjs.com/package/axios

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

Comments

0

From the documentation for the JQuery NPM Package

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.

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.