Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Im using electron to create a desktop app, now I need to get data from some remote APIs.

Could I use something like fetch or Reqwest on the Renderer process,or use any of the http npm packages on the Main process such as Request and use Electron's IPC to shuffle the data back and forth.

So what is the best way to do that.

like image 744
steve Avatar asked Dec 12 '25 05:12

steve


1 Answers

I prefer the native http and https packages. You can directly do a request in a render process. The following is a sample post request with error handling. Maybe there is a better solution out there - this is only my handling.

// 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();
like image 159
Tim S. Avatar answered Dec 14 '25 00:12

Tim S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!