【问题标题】:How to use jquery in node.js?如何在 node.js 中使用 jquery?
【发布时间】:2020-11-03 05:50:50
【问题描述】:

我使用 node.js,Firebase 函数。 我尝试实现一个非常简单的函数(在函数/index.js 中),它使用 POST 方法从第三方网站获取响应:

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";
});

但我有错误代码:

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) 

我不知道可能是什么问题... :(

【问题讨论】:

标签: javascript jquery node.js google-cloud-functions


【解决方案1】:

jQuery 不适合 Node.js,因为前者独立地包装和/或将属性应用到浏览器对象,例如 windowdocument。例如,jQuery 的 ajax 就利用了 window.XMLHttpRequest。

为了在本地处理这个问题,您需要利用 Node 的 http 包(使用它的 request 方法)或安装一个 NPM 包来为您简化它。我会推荐axios,因为它的 API 可以被浏览器或 Node 使用,但有很多合适的选项可供选择。

节点的 HTTP:https://nodejs.org/api/http.html

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

【讨论】:

    【解决方案2】:

    来自the documentation 用于 JQuery NPM 包

    要让 jQuery 在 Node 中工作,需要一个带有文档的窗口。 由于 Node 中本机不存在这样的窗口,因此可以模拟 jsdom 等工具。这对于测试目的很有用。

    【讨论】:

      猜你喜欢
      • 2011-07-19
      • 2011-05-17
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      相关资源
      最近更新 更多