如何使用带有Node.js的$.getJSON获取JSON数据

2024-05-01 22:02:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: nodedataobjectjsfunctionusersatmodule
1条回答
网友
1楼 · 发布于 2024-05-01 22:02:57

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

您现在处于后端。因此,这里的情况将略有不同。这不是您如何从后端请求,而是应该考虑使用一个本机模块来制作^ {CD2>}请求,它是^ {< CD2>}模块,并且使用它像

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

或者,如果您想使用类似getJson的东西,这里有一个^{}库,您可以像这样使用它

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

当然,您必须首先使用npm install get-json安装它

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

相关问题 更多 >