从JavaScript加载外部JavaScript库/脚本
我正在尝试使用JavaScript/Node.js构建控制台应用程序,下面的script.js在编译时抛出一个从JavaScript加载外部JavaScript库/脚本,javascript,jquery,node.js,compiler-errors,Javascript,Jquery,Node.js,Compiler Errors,我正在尝试使用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.ques
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();
});
如本帖所示;我希望这是因为我错过了JS库
有没有一种方法可以调用script.JS中的JS库而不创建单独的HTML文件?由于我没有构建前端web应用程序,因此不认为在Node.js代码中创建HTML文件有什么意义?,通常不需要使用jQuery,但如果您愿意,它可以作为
npm
模块提供。您需要安装它(npm install jquery
),然后require
它就像您的代码中require
dreadline
一样。完整详细信息(因为jQuery需要一个DOM环境)
但是,这里不需要jQuery。使用或类似的替代品。我怀疑
$。getJSON
甚至可以在Node.js中工作。这个$
看起来像是某个jQuery代码的复制/粘贴。axios将在节点和浏览器中完成任务,而不是jQuery。是一个带有承诺的http请求库。首先,将包添加到项目中:$npmi-saxios
获取请求的示例:()
您正在使用Nodejs。将jquery与require一起使用。类似var$=require('jquery');谢谢,我现在会继续使用
require
,但会研究http.request
。我得到了$。getJSON不是一个函数
错误,尽管我已经通过npm get json
@Sara安装了get json-实际上,不要尝试在Node.js上使用jQuery进行网络操作。出于好奇,我试了一下,它抱怨说试图从originnull
执行跨源请求。jQuery不是这份工作的合适工具。我理解,但我只是在这里时间不够,学习如何使用http。请求
需要一些时间time@Sara-如果你的时间不够,绝对不要尝试使用错误的工具来完成工作。只是看看例子。谢谢你的链接,我一定会在我的业余时间看看他们!我想了解更多关于Node.js的信息。很高兴它有所帮助。:)
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)
}