从 URL [Script Labs (Office) 中的 Javascript] 获取 html 内容

问题描述

简而言之,当通过 Excel 运行时,我试图从 Script Labs 环境内部的 url "http://anovamoeda.oinvestidordesucesso.com/IS/nmREPORT.asp?NM=2" 获取 html 内容一个简单的 fetch(url) 返回这个神秘的错误消息:

TypeError {}
 description: "Failed to fetch"
 message: "Failed to fetch"
 number: -2147418113
▶__proto__: TypeError
▶constructor: function TypeError()
 message: ""
 name: "TypeError"
▶toString: function toString()
▶__proto__: Error

我可以确定这是一个网络错误(承诺返回被拒绝),这看起来很奇怪,因为我也尝试从 API 获取 JSON 并且它工作正常(例如,对于那些愿意的人来说,https://api.binance.com/sapi/v1/system/status来试试)。首先,我认为这可能是由于我的 url 具有 html 内容,而不是 JSON,但这并不是说它无法解析信息,它甚至没有获取信息来尝试。我尝试向传递 {headers: {'Content-Type': 'text/html'}} 的 fetch 调用添加一个参数,但这不起作用。 (另外,我是 JS 的菜鸟。)

但我可以从 Google Scripts 内部获取信息,使用他们自己的 UrlFetchApp API 并简单调用该 fetch 方法

很高兴得到任何帮助,因为我找不到任何帮助。

解决方法

您没有显示足够的代码,所以我不确定您在做什么。该 URL 不返回 json:它是一个 html 文档。如果你想要 html 文档的文本,试试这个:

var response = await fetch("http://anovamoeda.oinvestidordesucesso.com/IS/nmREPORT.asp?NM=2");
if (response.ok) {
    var content = await response.text();
    // parse the content
    console.log(content);
}
else {
   // handle error response
}
,

我相信我知道发生了什么。据埋在 GitHub 深处的 this thread 说,Script Lab 只支持 https。我们生活的这个悲伤的世界。