如何使用 $.getJSON 和 Node.js 获取 JSON 数据 [英] How do you get JSON data using $.getJSON with Node.js
问题描述
我是 Node.js 的新手.我已经有一个前端 javascript 脚本,它使用 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){
promise 有问题,所以我只是把它注释掉了,如你所见.我在 $.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.5stationFunctionsNode.js:34
$.getJSON(theURL,function(data){
^
ReferenceError: $ is not defined
at Object.getTextWeatherUsingStation (C:Usersedwin.brownSitesdevdesktopdrupal-8.4.5stationFunctionsNode.js:34:13)
at Object.<anonymous> (C:Usersedwin.brownSitesdevdesktopdrupal-8.4.5
odeTestWData.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
的东西,这里是 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')
这篇关于如何使用 $.getJSON 和 Node.js 获取 JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!