【问题标题】:Consuming RESTful APIs using Electron使用 Electron 使用 RESTful API
【发布时间】:2021-02-26 13:34:52
【问题描述】:

我想在显示我的 Electron 应用程序的任何窗口之前对 RESTful API 发出一些请求(GET、POST、PUT ...)(使用 Electron 应用程序作为客户端)。是否可以使用ClientRequest 来执行此操作?谁能举个例子?

非常感谢。

【问题讨论】:

    标签: node.js rest spring-boot electron


    【解决方案1】:

    只需克隆这个 repo - git clone https://github.com/AldoHub/Electron-Weather.git

    同样的视频位于 - https://www.youtube.com/watch?v=5_r7UQvnbtQ。 您还需要注册https://weatherstack.com/ 并获取“您的 API 访问密钥”并将其粘贴到文件中

    Electron-Weather/src/public/functions.js
    

    在第 5 行

    await fetch(`http://api.weatherstack.com/current?access_key=<your_access_key>&query=${city}`)
    

    另外,要调试电子应用程序,请参阅链接 - https://discuss.atom.io/t/how-to-make-developer-tools-appear/16232/6 最后,要运行电子应用程序,请执行命令

    1. npm install or yarn install
    2. npm start or yarn start
    

    另一个 POST 示例:

    方法:POST

    网址:http://161.117.231.37/api/v1/login

    正文:

    {
        "email": "admin@gmail.com",
        "password": "12345678"
    }
    

    示例响应是:

    {
        "success": true,
        "data": {
            "expiresIn": 6000,
            "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSIsImlhdCI6MTYxNDMxNzM1MiwiZXhwIjoxNjE0MzIzMzUyfQ.wPcSA9Mx8PSLUgi1Okxwl8LBfx3Ia8m9bL5PEndcrs8",
            "type": "Admin",
            "verification": {
                "mobile": true,
                "email": true,
                "isProfileCompleted": 0,
                "isOnboardingComplete": false,
                "forcePasswordChange": true
            }
        }
    }
    

    现在,相同的代码是 函数.js

    const cityForm = document.querySelector("#weatherForm");
    
    document.addEventListener("DOMContentLoaded", (e) => {
        cityForm.addEventListener("submit", (e) => {
            e.preventDefault();
            if(document.querySelector("#email").value != ""){
                let conditionsDiv = document.querySelector("#conditions");
                if(conditionsDiv){
                    document.querySelector("main").removeChild(conditionsDiv);
                }
                getToken(document.getElementById("email").value, document.getElementById("password").value);
            }else{
                console.log("You must provide a email and password");
            }
        })
    })
    
    const getToken = async(_email, _password) => {
        let _body = {email: _email, password: _password}
        console.log({email: _email, password: _password})
        await fetch('http://161.117.231.37/api/v1/login',{
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, *cors, same-origin
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin', // include, *same-origin, omit
            headers: {
              'Content-Type': 'application/json'
              // 'Content-Type': 'application/x-www-form-urlencoded',
            },
            redirect: 'follow', // manual, *follow, error
            referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
            body: JSON.stringify({email: _email, password: _password}) // body data type must match "Content-Type" header
          })
        .then(res => res.json())
        .then(data => {
            console.log(data)
            let div = document.createElement("div");
            div.setAttribute("id", "conditions");
    
    
            let temp = document.createElement("div");
            let tempNode = document.createTextNode("Your token is this......" + data.data.token );
            temp.appendChild(tempNode);
    
            div.appendChild(temp);
            document.querySelector("main").appendChild(div);
    
        }).catch(err => console.log(err))
    
    }
    

    在 index.html 中,你有:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" href="../public/main.css" type="text/css" />
        <title>Electron Weather</title>
    </head>
    <body>
        
        <img id="hero" src="../public/images/taxi-autopilot.png" />
        <header>
            <h1>Electron <br/> Weather</h1>
            <p>illustration by <strong>Ouch.pics</strong></p>
        </header>
    
        <main>
            
            <p>Type the email and password to find out the token ...</p>
            <form method="POST" id="weatherForm">
                <input type="text" id="email" placeholder="Email Name" />
                <input type="text" id="password" placeholder="Password Name" />
                <input id="postSubmit" type="submit" value="Submit" />   
            </form>
        </main>
    
        <script src="../public/functions.js"></script>
    </body>
    </html>
    

    按两次 Ctrl + Shift +I 后,您会在电子应用程序中看到控制台窗口:

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多