【问题标题】:How to get specific data from API and use in function?如何从 API 获取特定数据并在函数中使用?
【发布时间】:2019-11-07 06:17:33
【问题描述】:

我正在尝试使用黑暗天空 API 在 nodejs 中构建天气应用程序。我有一个单独的 js 文件,并将我的预测信息保存在回调函数中。但是,我也想使用 Skycons 进行可视化。

这是我的 forecast.js。在那个脚本中,我得到了温度等信息,所以我还需要获取“图标”数据

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

这是 fetch 函数,我尝试在这个函数中调用和激活 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,我需要从黑暗天空 API 获取“图标”。除了我的预测 js,我如何获取这些数据?获取该数据并将其分配给变量并在另一个函数中使用

【问题讨论】:

    标签: javascript node.js api darksky


    【解决方案1】:

    看起来data 对象只能在响应 json 中访问,这意味着您需要在收到响应时访问 forcast.icon

    【讨论】:

    • 但我的响应 json 在另一个 js 中。每当我尝试提取 forecast.icon 时,它只是给了我一个字符串,而不是一个变量
    猜你喜欢
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2019-02-16
    相关资源
    最近更新 更多