如何使用带有Node.js的$.getJSON获取JSON数据
我是Node.js的新手。我已经有了一个前端javascript脚本,它使用API获取天气数据,如下所示:如何使用带有Node.js的$.getJSON获取JSON数据,json,node.js,drupal,Json,Node.js,Drupal,我是Node.js的新手。我已经有了一个前端javascript脚本,它使用API获取天气数据,如下所示: function getTextWeatherUsingStation(theStation){ theURL = 'https://api.weather.gov/stations/' + theStation + '/observations/current'; // return new Promise((resolve, reject) => {
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)
我读到你不能只使用图书馆。我将它包装成一个Node.js友好文件
module.exports = {
以及将功能更改为:
getTextWeatherUsingStation: function(theStation){
这是有问题的承诺,所以我只是评论了出来,你可以看到。
我在$.getJSON行中遇到了错误,并认为这是因为我没有包含jQuery,所以我使用npm安装了它
我仍然得到这个,不知道为什么:
....\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
…\drupal-8.4.5\stationFunctionsNode.js:34
$.getJSON(URL、函数(数据){
^
ReferenceError:$未定义
在Object.getTextWeatherUsingStation(C:\Users\edwin.brown\Sites\devdesktop\drupal-8.4.5\stationFunctionsNode.js:34:13)
对象上。(C:\Users\edwin.brown\Sites\devdesktop\drupal-8.4.5\nodeTestWData.js:8:18)
在模块处编译(Module.js:643:30)
在Object.Module._extensions..js(Module.js:654:10)
在Module.load(Module.js:556:32)
在tryModuleLoad时(module.js:499:12)
在Function.Module.\u加载(Module.js:491:3)
位于Function.Module.runMain(Module.js:684:10)
启动时(bootstrap_node.js:187:16)
在bootstrap_node.js:608:3
$。getJSON
是jQuery的前台函数,用于发出http
请求
你现在在后端。所以这里的情况会有点不同。这不是你如何从后端请求,而是应该考虑使用一个本地模块来制作<代码> HTTP < /COD>请求,这是<代码> HTTP 模块,并且使用它像
http.request(Options, function(res) { ...
或者,如果您想使用类似于getJson
的东西,这里有一个库,您可以像
getJSON('URL', function(error, response){..
当然,您必须首先使用npm install get json
然后在您的项目中使用,如
var getJSON=require('get-json')
I used request(url,(error,response,body)=>{if(!error&&response.statusCode==200){这些评论回复是否不允许格式化?并限制字符数?这wayNode.js很难回复您??该站点似乎是Drupal站点。Drupal的哪个版本?如果是Drupal 8,您是否在页面上包含了jquery(Drupal 8默认情况下不在页面上加载jquery)