简体   繁体   中英

Load external JavaScript libraries/scripts from JavaScript

I'm trying to build a console application using JavaScript/Node.js, the following script.js throws an ReferenceError: $ is not defined upon compilation:

//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();
});

As shown in this post; ReferenceError: $ is not defined I'm hoping its because I'm missing the JS libraries.

Is there a way I can call the JS libraries inside my script.js without creating a separate HTML file? As I'm not building a front end web application therefore don't see the point in creating a HTML file?

In Node.js code, you don't typically need to use jQuery, but if you do want to it's available as an npm module. You'd install it ( npm install jquery ) and then require it just like you require d readline in your code. Full details (since jQuery expects a DOM environment) in this answer .

But , there's no need for jQuery here. Use http.request or https.request or similar instead. I doubt $.getJSON will even work in Node.js.

The $ looks like it was a copy/paste from some jQuery code. Instead of jQuery, axios will get the job done in Node and in a browser. axios is an http request library with promises. First, add the package to the project: $ npm i -s axios .

Example get request: ( 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM