How do you get JSON data using $.getJSON with Node.js

天大地大妈咪最大 提交于 2021-02-17 05:39:28

问题


I'm new to Node.js. I already have a frontend javascript script that uses an API and gets weather data like so:

function getTextWeatherUsingStation(theStation){

 theURL = 'https://api.weather.gov/stations/' + theStation + '/observations/current';

    //    return new Promise((resolve, reject) => {

            $.getJSON(theURL,function(data){
            var myJSON = JSON.stringify(data)

I read that you can't just use a library as is. I converted it over to a Node.js friendly file by wrapping it in

module.exports = { 

and altering the function to:

getTextWeatherUsingStation: function(theStation){

It was having problem with promise so I just commented it out as you can see. I was getting errors on the $.getJSON line and figured it was because I hadn't included jQuery so I used npm to install that.

I'm still getting this and can't figure out why:

....\drupal-8.4.5\stationFunctionsNode.js:34
            $.getJSON(theURL,function(data){
            ^

ReferenceError: $ is not defined
    at Object.getTextWeatherUsingStation (C:\Users\edwin.brown\Sites\devdesktop\drupal-8.4.5\stationFunctionsNode.js:34:13)
    at Object.<anonymous> (C:\Users\edwin.brown\Sites\devdesktop\drupal-8.4.5\nodeTestWData.js:8: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

回答1:


$.getJSON is jQuery's function for front to make http requests.

You are on backend now. So things will be little different here. This is not how you make requests from backend instead should consider using one of the native modules to make http requests which is http module and you use it like

 http.request(Options, function(res) { ...

Or if you want to use something like getJson here is get-json library that you can use like

getJSON('URL', function(error, response){..

Ofcourse you'll have to install it first with npm install get-json

then use in your project like var getJSON = require('get-json')



来源:https://stackoverflow.com/questions/50261117/how-do-you-get-json-data-using-getjson-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!