如何使用带有Node.js的$ .getJSON获取JSON数据 [英] How do you get JSON data using $.getJSON with Node.js
问题描述
我是Node.js的新手.我已经有一个前端API脚本,该脚本使用API并获取天气数据,如下所示:
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 = {
并将功能更改为:
getTextWeatherUsingStation: function(theStation){
它在兑现承诺方面存在问题,因此您可以看到我将其注释掉了.我在$ .getJSON行上遇到错误,并认为这是因为我没有包括jQuery,所以我使用npm进行了安装.
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
推荐答案
$.getJSON
是jQuery的前端函数,用于发出 http
请求.
$.getJSON
is jQuery's function for front to make http
requests.
您现在处于后端.因此,这里的情况将有所不同.这不是您从后端发出请求的方式,而是应考虑使用本机模块之一发出 http
请求,即 http
模块,并且像这样使用
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) { ...
或者,如果您想使用类似 getJson
之类的方法,请使用 <您可以使用类似的code> get-json 库
Or if you want to use something like getJson
here is get-json
library that you can use like
getJSON('URL', function(error, response){..
当然,您必须先使用 npm install get-json
然后在您的项目中使用 var getJSON = require('get-json')
then use in your project like var getJSON = require('get-json')
这篇关于如何使用带有Node.js的$ .getJSON获取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!