2017-06-09 27 views
-2

我開始了一個項目,用我的樹莓派運行一個電子應用程序,我需要從露天天氣API獲取實際天氣。我對電子完全陌生,並沒有在Javascript中體驗過。所以我堅持從天氣API獲取數據到應用程序中。我可以將數據請求爲JSON或XML數據。我嘗試了不同的方式,我認爲它可能有效,但都失敗了。那麼有人能告訴我如何將API數據轉換爲電子嗎?將天氣API數據加載到電子中App

+0

歡迎這樣,這個問題真的是廣泛的,我建議你閱讀這https://stackoverflow.com/help/how-to-ask如果你可以添加一些你已經完成的代碼,人們可以更好地瞭解如何爲你提供幫助,下一次嘗試更具體。 – nramirez

+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(); 
    
+0

謝謝。這非常令人興奮,我需要幫助。 :) –