Reputation: 33
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... :(
Upvotes: 0
Views: 2550
Reputation: 1859
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
Upvotes: 1
Reputation: 2546
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.
Upvotes: 0