调用外部API后,Apps Script的doPost无法向客户端返回值的问题
解决Google Apps Script Web App doPost返回不支持类型的问题
问题现象
部署为Web App的Google Apps Script中,doPost方法调用外部API后返回报错:
The script completed but the returned value is not a supported return type.
直接返回硬编码JSON对象时,客户端(Postman/Bruno等)能正常获取响应;调用外部API后,控制台日志显示数据正常,但客户端收到上述错误。
问题原因
Google Apps Script的doPost函数不支持返回Promise对象。当前代码中doPost返回的是jokefunc().then(...)生成的Promise,而非同步的ContentService输出对象,这是导致报错的核心原因。
解决方案
将doPost声明为async函数,使用await等待外部API调用完成,同步返回合法的ContentService响应对象,同时完善错误处理逻辑。
修改后的完整代码
let respout = { "jokeid": 0, "errcode": 0, "errmsg": "na" }; async function doPost() { console.log('inside doPost func', respout); try { // 用await等待异步API调用完成,获取同步结果 const res = await jokefunc(); respout = { "jokeid": res.id, "errcode": 200, "errmsg": "success" }; console.log('resp out val', respout); // 同步返回ContentService对象 return ContentService.createTextOutput(JSON.stringify(respout)) .setMimeType(ContentService.MimeType.JSON); } catch (error) { console.log('Exception in doPost', error); // 异常时返回错误响应 respout = { "jokeid": 0, "errcode": 500, "errmsg": error.message }; return ContentService.createTextOutput(JSON.stringify(respout)) .setMimeType(ContentService.MimeType.JSON); } } async function jokefunc() { try { const API_URL = "https://official-joke-api.appspot.com/random_joke"; const response = UrlFetchApp.fetch(API_URL); const responseText = response.getContentText(); const jsonData = JSON.parse(responseText); console.log('Fetch called', jsonData); return jsonData; } catch (error) { console.error('Something went wrong', error); // 抛出错误,让上层doPost的catch捕获 throw error; } }
关键修改点
- 将doPost改为async函数:允许在函数内部使用
await处理异步操作,确保返回的是同步的ContentService对象而非Promise。 - 用await替代then链式调用:直接获取jokefunc的返回结果,避免返回Promise。
- 完善错误传递:jokefunc中捕获错误后抛出,让doPost的catch块处理,确保异常时也能返回合法的JSON响应,避免客户端收到无意义的错误页面。
内容的提问来源于stack exchange,提问作者Sri
相关产品推荐
相关产品推荐

