在Electron中,制作ajax请求的最佳方法是什么? [英] In Electron , what is the best way to make ajax requests?

查看:1686
本文介绍了在Electron中,制作ajax请求的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

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

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

这篇关于在Electron中,制作ajax请求的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆