【问题标题】:Electron Restful Api Without react or any other expressElectron Restful Api 没有反应或任何其他表达
【发布时间】:2020-07-08 06:08:15
【问题描述】:

我正在使用电子 js,但我面临的问题是编写 restful API。如果没有 react.js、express 和 falcon vue.js,几乎没有任何资源可以显示 API 的使用情况。我编写了 python API 来添加两个数字只是为了测试,但我不知道如何在没有任何其他语言(如 react/express/falcon)的情况下在电子中使用这些宁静的 API,因为它会增加我的学习曲线。 帮助表示赞赏。

注意:我的 API 是托管的

【问题讨论】:

    标签: javascript node.js ajax electron desktop-application


    【解决方案1】:

    您可以使用两种内置方法来代替 axiosjQuery Ajax 等框架,...

    获取:

    使用 Fetch API 非常简单。只需将 URL、要获取的资源的路径传递给 fetch() 方法即可。

    简单的GET方法:

    //simple GET method
    fetch('/js/users.json')
        .then(response => {
            // handle response data
        })
        .catch(err => {
            // handle errors
        });
    

    POSTDELETE、...等其他方法:

    // some data to post
    const user = {
        first_name: 'John',
        last_name: 'Lilly',
        job_title: 'Software Engineer'
    };
    
    // options of fetch
    const options = {
        method: 'POST',
        body: JSON.stringify(user),
        headers: {
            'Content-Type': 'application/json'
        }
    }
    
    fetch('https://reqres.in/api/users', options)
        .then(response => {
            // handle response data
        })
        .catch(err => {
            // handle errors
        });
    

    XML HttpRequest:

    XMLHttpRequest 是一个内置的浏览器对象,允许在 JavaScript 中发出 HTTP 请求。

    1. 创建 XMLHttpRequest:

      let xhr = new XMLHttpRequest();
      
    2. 初始化它,通常在新的 XMLHttpRequest 之后:

      xhr.open(method, URL, [async, user, password])
      
      • method – HTTP 方法。通常是"GET""POST"
      • URL – 请求的 URL,字符串,可以是 URL 对象。
      • async – 如果明确设置为 false,则请求是同步的,我们稍后会介绍。
      • userpassword – 基本 HTTP 身份验证的登录名和密码(如果需要)。
    3. 发送出去。

      xhr.send([body])
      

      此方法打开连接并将请求发送到服务器。可选的 body 参数包含请求正文。

      某些请求方法(如 GET)没有正文。其中一些喜欢 POST 使用 body 将数据发送到服务器。我们稍后会看到这样的例子。

    4. 监听 xhr 事件以获取响应。

      这三个事件是使用最广泛的:

      • load – 请求完成时(即使 HTTP 状态为 400 或 500),并且响应已完全下载。

      • error – 无法发出请求时,例如网络中断或 URL 无效。

      • progress – 在下载响应时定期触发,报告下载了多少。

        xhr.onload = function() {
            alert(`Loaded: ${xhr.status} ${xhr.response}`);
        };
        
        xhr.onerror = function() { // only triggers if the request couldn't be 
        made at all
             alert(`Network Error`);
        };
        
        xhr.onprogress = function(event) { // triggers periodically
        // event.loaded - how many bytes downloaded
        // event.lengthComputable = true if the server sent Content-Length 
        // header
        // event.total - total number of bytes (if lengthComputable)
            alert(`Received ${event.loaded} of ${event.total}`);
        };
        

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2012-11-22
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      相关资源
      最近更新 更多