如何将 JSON 响应存储在 Node.js 中的变量中?

How to store JSON response in variable in Node.js?

我正在努力从 API 获得响应并将其保存在变量中以便在 Node.js 中进一步使用它。也许我不知道语言是如何工作的。问题是:

// Objective, get current temperature of New Delhi in celcius

var request = require('request');

var url = "http://api.openweathermap.org/data/2.5/weather?id=1261481&appid=#####&units=metric";

request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    curTemp = JSON.parse(body).main.temp;  // curTemp holds the value we want
  }
})

// but I want to use it here
console.log(curTemp);

我想将来自 openweathermap(即 body.main.temp)的 JSON 响应存储到一个变量中。然后我会根据当前温度撰写一条推文。

请求是异步的。如果你想以这种方式编写异步代码,你应该使用 API 那个 returns 一个 Promise,例如axios. You can then use async/await 编写代码。

在Node.js中,都是关于回调(或稍后需要调用的函数)的。 所以您只需要创建一个 tweet 函数,并在您获得数据时调用它!

var request = require('request');
var url = "http://api.openweathermap.org/data/2.5/weather?id=1261481& appid=#####&units=metric";
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    curTemp = JSON.parse(body).main.temp;  // curTemp holds the value we want
    tweet(curTemp)
  }
})

// but I want to use it here
function tweet(data){
    console.log(data)
}

考虑到这不是异步编码的好方法。