IWuZhuo IWuZhuo - 2 days ago 5
HTTP Question

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.

Answer

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();
Comments