【问题标题】:Load external JavaScript libraries/scripts from JavaScript从 JavaScript 加载外部 JavaScript 库/脚本
【发布时间】:2019-03-12 06:35:35
【问题描述】:

我正在尝试使用 JavaScript/Node.js 构建控制台应用程序,以下 script.js 在编译时会抛出 ReferenceError: $ is not defined

//user input from command line
var readline = require('readline');

var rl = readline.createInterface({
 input: process.stdin,
 output: process.stdout
});

rl.question("Would you like to see which Car Types are available? Please type yes/no ", function(answer) {
// if yes, print search results to console in descending price order 
if (answer === 'yes'){

var results= "";
$.getJSON("https://techtest.rideways.com/dave/?pickup=3.410632,-2.157533&dropoff=3.410632,-2.157533", function(data){
results = JSON.parse(data);
}); 

console.log("The following Car Types are available:", results.options['car_type'], " - ", results.options['price']);
}else{
console.log("No worries, have a nice day!");
}
rl.close();
});

如本文所示; ReferenceError: $ is not defined 我希望是因为我缺少 JS 库。

有没有一种方法可以在我的 script.js 中调用 JS 库而无需创建单独的 HTML 文件?由于我没有构建前端 Web 应用程序,因此看不到创建 HTML 文件的意义吗?

【问题讨论】:

  • 你正在使用 Nodejs。将 jquery 与 require 一起使用。像 var $ = require('jquery');

标签: javascript jquery node.js compiler-errors


【解决方案1】:

在 Node.js 代码中,您通常不需要使用 jQuery,但如果您确实需要,它可以作为 npm 模块使用。你会安装它 (npm install jquery) 然后 require 它就像你在你的代码中 required readline 一样。完整的细节(因为 jQuery 需要一个 DOM 环境)in this answer.

但是,这里不需要 jQuery。请改用http.requesthttps.request 或类似名称。我怀疑$.getJSON 甚至可以在 Node.js 中工作。

【讨论】:

  • 谢谢,我现在会坚持使用require,但会关注http.request。尽管我已经通过 npm get-json 安装了 get-json,但我收到了 $.getJSON is not a function 错误
  • @Sara - 真的,不要尝试在 Node.js 上使用 jQuery 进行网络操作。出于好奇,我只是试了一下,它抱怨试图从来源null 发出跨域请求。 jQuery 只是不适合这项工作。
  • 我明白了,只是我在这里的时间不够,学习如何使用http.request需要一些时间
  • @Sara - 如果您时间不够,绝对不要尝试使用错误的工具来完成这项工作。只需寻找示例,like these
  • 感谢您提供的链接,我一定会在空闲时间查看它们!我想了解有关 Node.js 的更多信息。
【解决方案2】:

$ 看起来像是一些 jQuery 代码的复制/粘贴。 axios 将在 Node 和浏览器中完成工作,而不是 jQuery。 axios 是一个带有 Promise 的 http 请求库。首先,将包添加到项目中:$ npm i -s axios

获取请求示例:(run it on repl.it)

const axios = require('axios');

main();

function main() {
  return exampleRequest().then(renderResponseData)
}

function exampleRequest() {
  const url = 'https://techtest.rideways.com/dave/?pickup=3.410632,-2.157533&dropoff=3.410632,-2.157533';

  return axios.get(url)
}

function renderResponseData(response) {
  console.log(response.data)
}

【讨论】:

  • 很高兴它有帮助。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
  • 2022-12-21
  • 1970-01-01
相关资源
最近更新 更多