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... :(

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
SzB
  • 33
  • 8
  • 2
    There are many other better libraries than jquery that can be used for making HTTP requests in nodejs. – Doug Stevenson Nov 02 '20 at 21:37
  • If you want to do http request in node use either api provided directly by node [http](https://nodejs.org/api/http.html) or [https](https://nodejs.org/api/https.html) or use a module like [axios](https://github.com/axios/axios) – t.niese Nov 02 '20 at 21:45
  • Does this answer your question? [Why is $.ajax undefined when using jQuery on Node.js?](https://stackoverflow.com/questions/29191339/why-is-ajax-undefined-when-using-jquery-on-node-js) – Timar Ivo Batis Nov 02 '20 at 21:46

2 Answers2

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

Steve Hynding
  • 1,799
  • 1
  • 12
  • 22
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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Duncan_m
  • 2,526
  • 2
  • 21
  • 19