【问题标题】:How to run jQuery in node.js [duplicate]如何在 node.js 中运行 jQuery [重复]
【发布时间】:2018-08-06 05:01:57
【问题描述】:

我已经尝试过npm install jQuery --save 和我的节点文件var $ = require('jquery'); 但是,当我使用

运行我的节点文件时
$.getJSON('https://en.wikipedia.org/wiki/Washington,_D.C.', function(data) {
    //data is the JSON string
});

我得到了错误

TypeError: $.getJSON is not a function
    at Object.<anonymous> (C:\Users\Karim\node 2\tweetPic.js:16:3)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

我也尝试过使用

导入 jquery
require("jsdom").env("", function(err, window) {
if (err) {
    console.error(err);
    return;
}

var $ = require("jquery")(window);
});

只是返回

TypeError: require(...).env is not a function
    at Object.<anonymous> (C:\Users\Karim\node 2\tweetPic.js:3:18)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

我以类似的方式安装了 jsdom 包。我的 jquery 代码本身有问题吗?我该如何解决这个问题?

编辑:看来 jQuery 并不是我真正需要的。我只是要研究一种不同的方式来检索 json 数据。

【问题讨论】:

  • 您是否尝试在 Node.js 上安装 jQuery 以便发出简单的 HTTP 请求?
  • Nicholas 我正在尝试从特定 url 获取 json 数据。我不确定这是否会转化为简单的 HTTP 请求。
  • 这是一个简单的 HTTP 请求。省去麻烦,并按照下面@JeremyM. 的回答。 jQuery 主要是一个前端框架,仅包含用于发送 HTTP 请求的辅助函数。将它安装在服务器上只是为了做一些可以通过其他专门在服务器上运行的轻量级模块轻松完成的事情,例如request,这是一种过度杀伤力。
  • 卡里姆,如果你还在寻找解决方案,这是:(2018 年更新)var jsdom = require("jsdom");const { JSDOM } = jsdom;vconst { window } = new JSDOM();const { document } = (new JSDOM('')).window;global.document = document;var $ = jQuery = require('jquery')(window);

标签: javascript jquery json node.js


【解决方案1】:

抱歉,我不知道如何安装 jquery。但是您显然需要它来请求网站并获取 json。您可以为此使用request。希望对你有帮助。

你可以这样做:

request('https://en.wikipedia.org/wiki/Washington,_D.C.', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

【讨论】:

  • 你能解释一下为什么 console.log(body);会打印谷歌主页的 html 吗?我假设您的意思是打印华盛顿特区维基百科页面的 html。对吗?
  • 你是对的伙伴:)
  • 也许你可以验证我的回答?
  • 对不起。是的,这行得通。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-21
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
  • 2014-06-17
  • 1970-01-01
  • 2013-03-19
相关资源
最近更新 更多