在 Electron 中,发出 ajax 请求的最佳方式是什么?
In Electron , what is the best way to make ajax requests?
我正在使用 electron 创建桌面应用程序,现在我需要从一些远程 API 获取数据。
我可以在 Renderer 进程上使用 fetch 或 Reqwest 之类的东西,或者在 Main 进程上使用任何 http npm 包,例如 Request 并使用 Electron 的 IPC 来回打乱数据。
那么最好的方法是什么。
我更喜欢原生的 http 和 https 包。您可以直接在渲染过程中执行请求。以下是带有错误处理的示例 post 请求。也许有更好的解决方案 - 这只是我的处理方式。
// 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 创建桌面应用程序,现在我需要从一些远程 API 获取数据。
我可以在 Renderer 进程上使用 fetch 或 Reqwest 之类的东西,或者在 Main 进程上使用任何 http npm 包,例如 Request 并使用 Electron 的 IPC 来回打乱数据。
那么最好的方法是什么。
我更喜欢原生的 http 和 https 包。您可以直接在渲染过程中执行请求。以下是带有错误处理的示例 post 请求。也许有更好的解决方案 - 这只是我的处理方式。
// 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();