Google Apps Script中UrlFetchApp调用返回401 Unauthorized错误求助
Google Apps Script导出Sheet为PDF时出现401未授权错误
我遇到了401未授权错误,和某Stack Overflow问题描述完全一致,但现有解决方案都无效。我的代码参考了另一Stack Overflow案例,之前能正常运行,修改后出现问题,目前卡在UrlFetchApp.fetch()调用处。
以下是我的代码(包含测试函数):
const ss = SpreadsheetApp.getActiveSpreadsheet(); function testExportGoogleSheet() { const ssId = ss.getId(); const sh = ss.getSheets()[1]; const fileName = sh.getName(); const file = exportGoogleSheet(fileName, ssId, sh); MailApp.sendEmail('myEmailAddress', 'testSubject', 'testBody',{attachments : file}); } function exportGoogleSheet(fileName, ssId, sh) { let url, urlExt, gid; // Base URL url = 'https://docs.google.com/spreadsheets/d/' + ssId + '/export'; urlExt = '?format=pdf' + // The below parameters are optional... '&size=7' + '&scale=2' + '&fitw=true' + '&fzr=true' + '&portrait=false' + '&sheetnames=false' + '&printtitle=false' + '&pagenumbers=false' + '&gridlines=true' + '&horizontal_alignment=CENTER' + '&vertical_alignment=TOP' + '&attachment=true'; gid = '&gid=' + sh.getSheetId(); url += urlExt + gid; const token = ScriptApp.getOAuthToken(); const params = { method: 'GET', headers: { 'authorization': 'Bearer ' + token } }; //'muteHttpExceptions': true, //'oAuthServiceName': 'spreadsheets', //'oAuthUseToken': 'always', const blob = UrlFetchApp.fetch(url, params).getBlob().setName(fileName + '.pdf'); return blob; }
错误信息:
Exception: Request failed for https://docs.google.com returned code 401. Truncated server response: <HTML> <HEAD> <TITLE>Unauthorized</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1>Unauthorized</H1> <H2>Error 401</H2> </BODY> </HTML>
我的appsscript.json配置:
{ "timeZone": "myTimeZone", "dependencies": { }, "exceptionLogging": "STACKDRIVER", "runtimeVersion": "V8", "oauthScopes": [ "https://www.googleapis.com/auth/spreadsheets.currentonly", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/script.send_mail", "https://www.googleapis.com/auth/forms.currentonly", "https://www.googleapis.com/auth/script.container.ui" ] }
排查建议:
- 调整权限范围:将
https://www.googleapis.com/auth/spreadsheets.currentonly替换为https://www.googleapis.com/auth/spreadsheets全权限,导出PDF可能需要超出当前文档的权限范围。修改后重新授权脚本。 - 完善请求参数:取消注释
oAuthServiceName和oAuthUseToken配置,添加到请求参数中:const params = { method: 'GET', headers: { 'authorization': 'Bearer ' + token }, oAuthServiceName: 'spreadsheets', oAuthUseToken: 'always', muteHttpExceptions: true // 可选,方便查看完整错误响应 }; - 验证Token有效性:添加日志打印Token的权限信息(注意不要泄露Token),确认包含spreadsheets相关权限:
Logger.log(ScriptApp.getOAuthToken()); // 可将Token放到Google OAuth2 Playground验证权限范围 - 检查URL拼接:确认生成的
url中gid参数正确,没有重复的?或参数冲突。可以打印url直接在浏览器中访问,测试是否能正常下载PDF(需登录同账号)。 - 重新授权脚本:删除脚本的现有授权(脚本编辑器→右上角头像→管理谷歌账号→安全→第三方应用访问→找到对应脚本删除),然后重新运行
testExportGoogleSheet触发授权流程。
内容的提问来源于stack exchange,提问作者Jumpy73
相关产品推荐
相关产品推荐

