使用fetch调用Apps Script Web App时doPost未触发,报doGet未找到
问题解决指南
核心问题:客户端请求配置错误
你的JS客户端代码里,fetch(url, {optionsin})的写法是错的——这会把请求配置包装成一个额外的对象,导致fetch忽略你设置的POST方法,改用默认的GET请求调用Web App。而你的脚本只实现了doPost函数,所以就会触发"Script function not found: doGet"错误。Bruno工具能正常工作,是因为你在工具里正确配置了POST请求。
分步解决
1. 修正fetch调用参数
把fetch(url, {optionsin})改成直接传入optionsin变量:
fetch(url, optionsin)
2. 给doPost添加合法响应
当前doPost函数没有返回任何内容,fetch后续尝试解析response.json()会报错。修改Apps Script代码,返回标准的JSON响应:
function doPost(e) { console.log('Posted data from client is..',JSON.stringify(e)); // 返回JSON格式的成功响应 return ContentService.createTextOutput(JSON.stringify({ status: "success", receivedData: e })) .setMimeType(ContentService.MimeType.JSON); }
3. 确认Web App部署配置
部署Web App时要注意:
- 执行权限选择「任何人,甚至匿名」(如果不需要用户身份验证)
- 每次修改代码后,必须重新部署并选择「新版本」,否则旧代码会继续生效
修正后的完整客户端代码
const url = "https://script.google.com/macros/s/myscriptid/exec"; let appbody = { "fruit_name" : "Orange", "qty" : "210" } let optionsin = { "headers" : { "Content-Type": "application/json" }, "method": "POST", "body": JSON.stringify(appbody) } function samplefunc() { try { console.log("About to call fetch") fetch(url, optionsin) .then(response => { // 先检查响应状态是否正常 if (!response.ok) throw new Error(`请求失败,状态码:${response.status}`); return response.json(); }) .then(result => { console.log('接口返回结果', result); }) } catch (error) { console.log('调用fetch时出错', error.message) } } samplefunc();
内容的提问来源于stack exchange,提问作者Sri
相关产品推荐
相关产品推荐

