JavaScript HTTP POST无法触发Google Apps Script函数问题求助
问题描述
尝试数小时通过JavaScript向Google Apps Script Web应用发送POST数据,期望触发邮件发送功能,但代码运行后无报错也无任何反应。
相关代码
HTML代码
<!DOCTYPE html> <html> <head> <!--Import JQUERY--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="script.js"></script> </head> <body> <button type="button" onclick="submitClicked()">submit</button> </body> </html>
前端JavaScript代码
function submitClicked() { sendData(); } function sendData() { console.log("running"); const url = "https://script.google.com/a/macros/limitlessflight.com/s/AKfycbyAhx3wCRR4fS30ZrVpFpe-lxksRjn8ZWTUmTj5YlbmD8wG2PlzzXzDNUUaS8ntu09LBQ/exec"; var xhr = new XMLHttpRequest(); xhr.open("POST", url, true); xhr.send(JSON.stringify({ value: "hello" })); console.log("done"); }
Google Apps Script代码
单独运行或通过GET请求访问时可正常发送邮件,已添加doGet(e)测试GET请求:
function doPost(e) { emailForm(e); } function doGet(e) { emailForm(e); } function emailForm(data) { MailApp.sendEmail({ to: "youremailhere@emailhere.com", subject: "Test Email", htmlBody: data }); }
问题排查与解决
1. 补全请求头与错误监听
前端发送POST请求时未设置Content-Type,导致GAS无法解析JSON格式的请求体;同时缺少请求状态监听,无法排查请求是否成功。修改前端代码:
function sendData() { console.log("running"); const url = "https://script.google.com/a/macros/limitlessflight.com/s/AKfycbyAhx3wCRR4fS30ZrVpFpe-lxksRjn8ZWTUmTj5YlbmD8wG2PlzzXzDNUUaS8ntu09LBQ/exec"; var xhr = new XMLHttpRequest(); xhr.open("POST", url, true); // 设置请求头,告知GAS请求体为JSON格式 xhr.setRequestHeader("Content-Type", "application/json"); // 监听请求结果 xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { console.log("请求成功:", xhr.responseText); } else { console.error("请求失败:", xhr.statusText); } }; xhr.onerror = function() { console.error("网络请求错误"); }; xhr.send(JSON.stringify({ value: "hello" })); console.log("done"); }
2. 修正GAS数据解析与响应返回
GAS的doPost(e)中,POST请求的JSON数据存储在e.postData.contents中,直接传递e会导致邮件内容显示为对象字符串;同时需要返回响应,避免前端请求异常。修改GAS代码:
function doPost(e) { // 解析POST请求的JSON数据 const data = JSON.parse(e.postData.contents); emailForm(data); // 返回成功响应 return ContentService.createTextOutput(JSON.stringify({status: "success"})).setMimeType(ContentService.MimeType.JSON); } function doGet(e) { emailForm(e.parameter); return ContentService.createTextOutput(JSON.stringify({status: "success"})).setMimeType(ContentService.MimeType.JSON); } function emailForm(data) { // 将数据转为可读的HTML格式 const htmlContent = `<p>收到的数据:</p><pre>${JSON.stringify(data, null, 2)}</pre>`; MailApp.sendEmail({ to: "youremailhere@emailhere.com", subject: "Test Email", htmlBody: htmlContent }); }
3. 检查Web应用部署设置
确保GAS Web应用部署时:
- 执行权限选择「任何人,甚至匿名」(测试阶段可使用,后续按需调整)
- 修改代码后重新部署新版本,避免缓存旧代码
内容的提问来源于stack exchange,提问作者Zane Jensen
相关产品推荐
相关产品推荐

