Google Apps Script UrlFetchApp返回未授权错误401不工作



我正在尝试使用谷歌文档发送和电子邮件。这是我使用的代码:

function sendHTMLtemp(){
const id = '1HC3ADjGE24ShOXeK_CYISGGIV7U0scJeXQ8o9oyu6vY';
const url = 'https://docs.google.com/document/d/'+id+'/export?format=html';
const param ={
mehtod : "get",
headers : {
"Authorization":"Bearer "+ScriptApp.getOAuthToken()
},
muteHttpExceptions:true
}
const html = UrlFetchApp.fetch(url,param);
Logger.log(html)
}

但是我得到这个错误"Unauthorized error 401.":

<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>

当我看到你的脚本时,如果你的Google Apps脚本只有你的显示脚本,我认为范围只有https://www.googleapis.com/auth/script.external_request。如果我的猜测是正确的,我认为在你目前的情况下,范围可能是不够的。因此,请按如下方式修改您的脚本:

修改脚本:

function sendHTMLtemp() {
const id = '1HC3ADjGE24ShOXeK_CYISGGIV7U0scJeXQ8o9oyu6vY';
const url = 'https://docs.google.com/document/d/' + id + '/export?format=html';
const param = {
mehtod: "get",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
}
const html = UrlFetchApp.fetch(url, param);
Logger.log(html)
// DriveApp.getFiles(); // <--- This comment line is used for automatically detecting the scope of "https://www.googleapis.com/auth/drive.readonly" by the script editor. So, please don't remove this comment.
}
  • 在这个修改中,使用了// DriveApp.getFiles();的注释行。此注释行用于脚本编辑器自动检测https://www.googleapis.com/auth/drive.readonly的作用域。这样,你的错误就可以消除了。所以,请不要删除这条评论。

  • 当这个修改后的脚本运行时,将打开一个用于授权范围的对话框。所以,请授权范围。这样,脚本就运行了。

  • 我认为在您的情况下,范围也可以设置为清单文件(appsscript.json)。但是,在这种情况下,作用域是固定的。我觉得这可能不适合你的情况。因此,我建议使用脚本编辑器自动检测作用域。

相关内容

最新更新