我开始了一个项目,我的树莓派运行电子应用程序,我需要从开放天气API获取实际天气。我对电子全新,而不是Javascript经验丰富。因此,我无法将天气API中的数据导入应用程序。我可以将数据请求为JSON或XML数据。我尝试了不同的方式,我认为它可能会起作用,但它们都失败了。那么有人可以告诉我如何将API数据整合到电子中吗?
答案 0 :(得分:0)
启动API请求的最简单方法是使用axios。
设置项目后(您可以关注Getting Started),请按以下步骤操作:
npm install --save axios
main.js
。main.js
之前的某处index.html
内加载</body>
。将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();