【问题标题】:How do you get JSON data using $.getJSON with Node.js如何使用 $.getJSON 和 Node.js 获取 JSON 数据
【发布时间】:2018-05-09 19:57:34
【问题描述】:

我是 Node.js 的新手。我已经有一个使用 API 并获取天气数据的前端 javascript 脚本,如下所示:

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){

promise 有问题,所以我只是将其注释掉,如您所见。 我在 $.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

【问题讨论】:

  • Node.js ????该站点似乎是一个 Drupal 站点。什么版本的 Drupal?如果是 Drupal 8,你是否在页面上包含了 jquery(Drupal 8 默认情况下不会在页面上加载 jquery)

标签: json node.js drupal


【解决方案1】:

$.getJSON 是 jQuery 的函数,用于前端发出 http 请求。

您现在在后端。所以这里的情况会有所不同。这不是您从后端发出请求的方式,而是应该考虑使用本机模块之一来发出 http 请求,即 http 模块,您可以像使用它一样

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

或者,如果您想使用类似 getJson 的东西,这里是 get-json 库,您可以像这样使用

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

当然你必须先用npm install get-json安装它

然后在你的项目中使用var getJSON = require('get-json')

【讨论】:

  • 我使用了 request(url, (error, response, body) => { if (!error && response.statusCode === 200) {
  • 这些评论回复是否不允许格式化?并限制字符数?很难以这种方式回复你
猜你喜欢
  • 2018-01-09
  • 1970-01-01
  • 2013-02-01
  • 2012-07-07
  • 1970-01-01
  • 2013-10-03
  • 2020-07-22
  • 1970-01-01
  • 2012-01-18
相关资源
最近更新 更多