Google Apps Script登录重定向与数据验证故障排查求助
解决Google Apps Script Web App登录时的Google Docs错误问题
问题场景
在Google Sites搭建的网站中,注册流程通过Google Forms将数据同步至Google Sheets,登录按钮关联Google Apps Script开发的Web App,预期验证Sheets中的邮箱和密码后跳转至指定页面,但提交登录信息时出现以下错误:
An error occurred in Google Docs. Try reloading the page or visiting it again in a few minutes.
To learn more about Google Docs editors, visit our Help Center.
We apologize for the inconvenience.
- The Google Docs team
错误原因及修复方案
1. 修复代码语法错误
原code.gs中if(loggedIn)块缺少闭合大括号,导致脚本执行时触发语法错误,这是引发服务器报错的核心原因。
修正后的code.gs:
function doGet(e) { return HtmlService.createHtmlOutputFromFile('login'); } function doPost(e) { var email = e.parameter.email; var password = e.parameter.password; // 验证Google Sheets中的凭据 var sheet = SpreadsheetApp.openById('YOUR_SPREADSHEET_ID').getSheetByName('Utenti_registrati'); var data = sheet.getDataRange().getValues(); var loggedIn = false; for (var i = 1; i < data.length; i++) { if (data[i][0] == email && data[i][1] == password) { loggedIn = true; break; } } if (loggedIn) { // 返回JSON格式的成功状态,由客户端处理跳转 return ContentService.createTextOutput(JSON.stringify({success: true})) .setMimeType(ContentService.MimeType.JSON); } else { return ContentService.createTextOutput(JSON.stringify({success: false, message: "Email o password errati. Riprova."})) .setMimeType(ContentService.MimeType.JSON); } }
2. 优化表单提交逻辑
改用客户端fetch API提交表单,避免直接form post可能引发的跨域或权限问题,同时提升交互体验。
修正后的login.html:
<!DOCTYPE html> <html> <head> <base target="_top"> <script> document.addEventListener('DOMContentLoaded', function() { const form = document.getElementById('loginForm'); form.addEventListener('submit', function(e) { e.preventDefault(); const formData = new FormData(this); fetch(this.action, { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { if (data.success) { alert('Login riuscito! Reindirizzamento in corso...'); window.location.href = 'https://sites.google.com/view/appuntiig/visualizza-appunti'; } else { alert(data.message); } }) .catch(error => { console.error('Errore:', error); alert('Si è verificato un errore durante il login.'); }); }); }); </script> </head> <body> <form id="loginForm" method="post" action="<?= ScriptApp.getService().getUrl() ?>"> Email: <input type="email" name="email" required><br> Password: <input type="password" name="password" required><br> <input type="submit" value="Accedi"> </form> </body> </html>
3. 检查Web App部署设置
重新部署Web App时,确保以下配置正确:
- 执行方式:选择「我(你的Google账号)」,确保脚本以拥有Sheets访问权限的账号执行
- 权限设置:选择「任何人,甚至匿名」(若允许未登录Google账号的用户使用登录功能)
- 部署完成后复制新生成的Web App URL,更新Google Sites中登录按钮的关联链接
4. 验证Sheets权限
确认部署Web App的Google账号拥有目标Google Sheets的编辑权限,避免读取数据时触发权限错误。
内容的提问来源于stack exchange,提问作者Manpreet Singh
相关产品推荐
相关产品推荐

