我在Google中编写一个脚本,从API中检索一个值。该API每10秒提供一次text/event-stream
响应。有没有一种不使用异步函数或事件侦听器来检索单个响应的方法?我在JavaScript方面不太胜任,但由于我在Google中工作,异步函数和事件侦听器似乎无法正常工作。根据我到目前为止所了解到的,使用text/event-stream
响应的唯一方法是使用EventSource
,但我无法使它与Google一起工作。
不过,我的目标只是从端点检索一个响应,所以在Google中实现这一点的任何方法都是很棒的。这里是端点,以防有帮助:
因为我无法在Google工作表中使用EventStream
,所以我尝试使用在这里找到的一个多功能:https://github.com/amvtek/EventSource/blob/master/dist/eventsource.js。
然后运行它时:
function getRplantTotal() {
var source = new EventSource('https://pool.rplant.xyz/api2/poolminer2x/raptoreum/RThRfoQJg8qsoStLk7QdThQGmpbFUCtvnk/UlRoUmZvUUpnOHFzb1N0TGs3UWRUaFFHbXBiRlVDdHZua3x4');
source.addEventListener("message", function(e) {
console.log(e.data);
});
}
但这只是产出:
3:11:49 PM Notice Execution started
3:11:49 PM Notice Execution completed
发布于 2021-10-21 06:06:15
我相信你的目标如下。
https://pool.rplant.xyz/api2/poolminer2x/raptoreum/RThRfoQJg8qsoStLk7QdThQGmpbFUCtvnk/UlRoUmZvUUpnOHFzb1N0TGs3UWRUaFFHbXBiRlVDdHZua3x4
的URL检索第一个值,并希望在Google电子表格中使用检索到的值。问题和解决办法:
当我看到https://github.com/amvtek/EventSource/blob/master/dist/eventsource.js
时,请求似乎是用XMLHttpRequest运行的。在Google脚本中,使用UrlFetchApp,不能使用XMLHttpRequest。我想这可能是你当前问题的原因。但不幸的是,在现阶段,这不能在Google脚本中使用text/event-stream
类型。当UrlFetchApp请求您的URL时,它看起来就像无限循环。这就是目前的情况。
因此,从My goal is just to retrieve one response from the endpoint though, so any way I can accomplish that in Google Sheets would be great.
和上述情况,我想提出一个解决办法。当您在Google电子表格上运行脚本时,使用Javascript从URL中检索值如何?Google脚本可以使用对话框和侧栏从Javascript端检索值。从您的问题中,当使用Javascript时,可以检索值。我想这个可能会被利用。当这个解决方案反映在Google脚本中时,如下所示。
示例脚本:
Google脚本端:Code.gs
请将以下脚本复制并粘贴到Google电子表格脚本编辑器的脚本文件中。
// Please run this function.
function main() {
SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile("index"), "sample");
}
function getValues(e) {
const obj = JSON.parse(e); // This is the 1st value from the URL of "https://pool.rplant.xyz/api2/poolminer2x/raptoreum/RThRfoQJg8qsoStLk7QdThQGmpbFUCtvnk/UlRoUmZvUUpnOHFzb1N0TGs3UWRUaFFHbXBiRlVDdHZua3x4"
console.log(obj)
// DriveApp.createFile("sample.txt", e); // When you use this, the retrieved value can be created as a text file.
}
Javascript端:index.html
请将以下脚本复制并粘贴到Google电子表格脚本编辑器的HTML文件中。请将文件名设置为index.html
。
Values are retrieving now. Please wait. After the values were retrieved, this dialog is automatically closed.
<script>
var source = new EventSource('https://pool.rplant.xyz/api2/poolminer2x/raptoreum/RThRfoQJg8qsoStLk7QdThQGmpbFUCtvnk/UlRoUmZvUUpnOHFzb1N0TGs3UWRUaFFHbXBiRlVDdHZua3x4');
source.addEventListener("message", function(e) {
source.close();
google.script.run.withSuccessHandler(google.script.host.close).getValues(e.data);
});
</script>
main()
函数。这样,在电子表格上打开一个对话框,使用Javascript从URL中检索值,当第一个值被检索时,这些值被发送到Google脚本端。因此,您可以在getValues
函数中使用检索到的值。注意:
参考文献:
https://stackoverflow.com/questions/69654650
复制相似问题