在Electron中,发出Ajax请求的最佳方法是什么?

ste*_*eve 3 ajax jquery http node.js electron

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

我可以在Renderer进程中使用fetch或Reqwest之类的东西,还是在Main进程中使用任何http npm程序包(例如Request),并使用Electron的IPC来回随机播放数据。

那么什么是最好的方法。

小智 8

我更喜欢本机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();
Run Code Online (Sandbox Code Playgroud)