繁体   English   中英

在Electron中,制作ajax请求的最佳方法是什么?

[英]In Electron , what is the best way to make ajax requests?

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

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

那么最好的方法是什么呢。

我更喜欢原生的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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM