【问题标题】:In Electron , what is the best way to make ajax requests?在 Electron 中,发出 ajax 请求的最佳方式是什么?
【发布时间】:2017-04-12 10:08:32
【问题描述】:

我正在使用电子创建桌面应用程序,现在我需要从一些远程 API 获取数据。

我可以在 Renderer 进程中使用 fetch 或 Reqwest 之类的东西,或者在 Main 进程中使用任何 http npm 包,例如 Request 并使用 Electron 的 IPC 来回打乱数据。

那么最好的方法是什么。

【问题讨论】:

    标签: jquery ajax node.js http electron


    【解决方案1】:

    我更喜欢原生的 http 和 https 包。您可以直接在渲染过程中执行请求。以下是带有错误处理的示例发布请求。也许有更好的解决方案 - 这只是我的处理方式。

    // You Key - Value Pairs
    var postData = querystring.stringify({
    
        key: "value"
    
    });
    
    
    // Your Request Options
    var options = {
    
        host: "example.com",
        port: 443,
        path: "/path/to/api/endpoint",
        method: 'POST',
        headers: {
    
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(postData)
    
        }
    
    };
    
    
    // The Request
    var request = https.request(options, function(response) {
    
        response.on('data', function(chunk) {
    
            if (chunk) {
    
                var data = chunk.toString('utf8');
                // holds your data
    
            }
    
    
        });
    
    }).on("error", function(e) {
    
        // Some error handling
    
    });
    
    
    //optionally Timeout Handling
    request.on('socket', function(socket) {
    
        socket.setTimeout(5000);
    
        socket.on('timeout', function() {
    
            request.abort();
    
        });
    
    });
    
    request.write(postData);
    request.end();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2012-03-30
      • 2015-12-20
      • 2013-12-05
      • 1970-01-01
      相关资源
      最近更新 更多