Google Apps Script UrlFetchApp返回401未授权错误无法正常调用
问题原因
- 代码存在拼写错误:请求参数中标记请求方法的
method字段被错写为mehtod,导致UrlFetchApp无法正确加载请求配置,请求方法、鉴权头均未按预期传递。 - OAuth权限范围缺失:Apps Script默认生成的访问令牌未携带Google文档读取、外部请求的对应权限,服务端校验时会直接判定为未授权请求,返回401状态码。
修复方案
- 修正拼写错误:将参数项
mehtod: "get"修改为method: "get"。 - 补充脚本权限:
- 打开Apps Script编辑器,点击左侧设置图标,勾选「在编辑器中显示appsscript.json清单文件」
- 回到文件列表打开
appsscript.json,在oauthScopes字段中加入所需权限,参考配置:
{ "timeZone": "Asia/Shanghai", "exceptionLogging": "STACKDRIVER", "runtimeVersion": "V8", "oauthScopes": [ "https://www.googleapis.com/auth/documents.readonly", "https://www.googleapis.com/auth/script.external_request" ] }
- 移除冗余的手动鉴权头配置:配置对应权限后,UrlFetchApp请求Google自有服务会自动携带合法鉴权令牌,手动拼接Bearer token反而可能出现格式不兼容问题。
- 调整日志打印逻辑:
UrlFetchApp.fetch返回的是响应对象,直接打印无法拿到HTML内容,需要调用getContentText()方法提取响应文本。
修正后完整可运行代码
function sendHTMLtemp(){ const id = '1HC3ADjGE24ShOXeK_CYISGGIV7U0scJeXQ8o9oyu6vY'; const url = 'https://docs.google.com/document/'+id+'/export?format=html'; const param ={ method : "get", muteHttpExceptions:true } const resp = UrlFetchApp.fetch(url,param); const html = resp.getContentText(); Logger.log(html); }
运行前提:脚本当前绑定的账号必须对目标ID对应的Google文档拥有查看权限,否则仍会返回权限类错误。
内容的提问来源于stack exchange,提问作者Andrea Quiroz
相关产品推荐
相关产品推荐

