如何从API获取特定数据并在函数中使用?

我正在尝试使用Dark-sky API在Node.js中构建气象应用程序。我得到了一个单独的js文件,并将预测信息保留在回调函数中。但是,我也想使用Skycons进行可视化。

这是我的Forecast.js。在该脚本中,我得到了温度等信息,因此我也需要获取“ icon”数据

const request = require('request')


const getWeather = (latitude,longitude,callback) => {

    const url = 'https://api.darksky.net/forecast/b0854aec02e1655c7203e05c7d77dfd1/' + latitude + ',' + longitude + '/?units=si'

    request({
        url: url,json: true
    },(error,{
        body /* "response " evezine response object icindeki "body" birbasa daxil edirem function-a*/
    }) => {
        if (error) {
            callback('Unable to connect to weather service!',undefined)
        } else if (body.error) {
            callback('Unable to find location'.undefined)
        } else {
            callback(undefined,'It is currently ' + body.currently.temperature + '°C out in ' + body.timezone + '. Weather ' + body.daily.data[0].summary + ' There is a ' + (body.currently.precipProbability * 100) + '% chance of rain.'
            )
        }
    })

}

module.exports = getWeather

这是获取功能,我尝试在此功能中调用和激活Skycons。但我无法从API获取“图标”数据。

const weatherForm = document.querySelector("form");
const search = document.querySelector("input");

const messageone = document.querySelector("#message-1");
const messageTwo = document.querySelector("#message-2");

const skycons = new Skycons({
  color: '#222'
})
skycons.set('icon','clear-day');
skycons.play();

const icon = data.forecast.icon;


weatherForm.addEventListener("submit",e => {
  e.preventDefault();

  const location = search.value;

  messageone.textContent = "Please wait....";
  messageTwo.textContent = "";

  fetch(
    "http://localhost:4000/weather?address=" + encodeURIComponent(location)
  ).then(response => {
    response.json().then(data => {
      if (data.error) {
        messageone.textContent = data.error;
      } else {
        messageone.textContent = data.location;
        messageTwo.textContent = data.forecast;

      }
      currentSkycons(icon,document.getElementById('icon'));
    });
  });


  messageone.textContent;
  messageTwo.textContent;
});

function currentSkycons(icon,iconID) {

  const currentIcon = icon.replace(/-/g,"_").toUppercase();
  skycons.play();
  return skycons.set(iconID,Skycons[currentIcon]);

}

但是要使用Skycons,我需要从Dark-sky API获取“ icon”。除了我的预测js,如何获取这些数据?将该数据获取并分配给变量并在另一个函数中使用

domeimei 回答:如何从API获取特定数据并在函数中使用?

似乎data对象只能在响应json中访问,这意味着您需要在响应时访问forcast.icon

本文链接:https://www.f2er.com/3147120.html

大家都在问