使用Electron使用RESTful API

时间:2017-09-03 16:04:06

标签: node.js rest spring-boot electron

在显示我的Electron应用程序的任何窗口(使用Electron app作为客户端)之前,我想为RESTful API做一些请求(GET,POST,PUT ...)。是否可以使用ClientRequest来执行此操作?有人会有一个例子吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

只需克隆这个 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"
}

enter image description here

示例响应是:

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

enter image description here 现在,相同的代码是 函数.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 两次后,您会在电子应用程序中看到控制台窗口: enter image description here

相关问题