将天气API数据加载到电子App中

时间:2017-06-09 20:08:57

标签: javascript raspberry-pi electron

我开始了一个项目,我的树莓派运行电子应用程序,我需要从开放天气API获取实际天气。我对电子全新,而不是Javascript经验丰富。因此,我无法将天气API中的数据导入应用程序。我可以将数据请求为JSON或XML数据。我尝试了不同的方式,我认为它可能会起作用,但它们都失败了。那么有人可以告诉我如何将API数据整合到电子中吗?

1 个答案:

答案 0 :(得分:0)

启动API请求的最简单方法是使用axios

设置项目后(您可以关注Getting Started),请按以下步骤操作:

  1. 安装Axios npm install --save axios
  2. 在项目的文件夹中创建main.js
  3. main.js之前的某处index.html内加载</body>
  4. 将JavaScript代码放在main.js

    const axios = require('axios');
    
    function fetchData() {
      // you might need the next line, depending on your API provider.
      axios.defaults.headers.post['Content-Type'] = 'application/json';
      axios.post('api.example.com', {/* here you can pass any parameters you want */})
      .then((response) => {
        // Here you can handle the API response
        // Maybe you want to add to your HTML via JavaScript?
        console.log(response);
      })
      .catch((error) => {
        console.error(error);
      });
    }
    
    
    // call the function to start executing it when the page loads inside Electron.
    fetchData();