使用Google Apps Script调用Zoom API PATCH接口报错的解决方法
问题描述
使用Google Apps Script(GAS)调用Zoom API的「更新用户设置」接口发送PATCH请求时,出现错误:SyntaxError: Unexpected end of JSON input。已确认该API在Postman中可正常运行,且OAuth令牌有效,代码如下:
function test_updateUserSetting(){ let userEmail = "Zoom User Email" let url = 'https://api.zoom.us/v2/users/' + userEmail + '/settings' const token = getToken() // get OAuth token Logger.log(token) let raw = JSON.stringify({ "feature": { "webinar": true, "webinar_capacity": 500 } }); let requestOptions = { 'method' : 'PATCH', 'contentType': 'application/json', 'headers': {'Authorization' : 'Bearer ' + token}, 'payload': raw }; let response = UrlFetchApp.fetch(url, requestOptions); let user = JSON.parse(response.getContentText()); console.log(user) }
解决方案
错误核心原因是:Zoom的「更新用户设置」接口成功执行后会返回204 No Content状态码,没有JSON响应体。此时调用JSON.parse(response.getContentText())解析空字符串,就会触发Unexpected end of JSON input错误。同时需要补充调试和请求配置优化,修改后的代码如下:
function test_updateUserSetting(){ let userEmail = "Zoom User Email" // 编码用户邮箱,避免特殊字符导致URL无效 let url = 'https://api.zoom.us/v2/users/' + encodeURIComponent(userEmail) + '/settings' const token = getToken() // 获取OAuth令牌 let requestBody = { "feature": { "webinar": true, "webinar_capacity": 500 } }; let requestOptions = { 'method' : 'PATCH', 'contentType': 'application/json', 'headers': { 'Authorization' : 'Bearer ' + token, 'Accept': 'application/json' // 明确指定接受JSON格式响应 }, 'payload': JSON.stringify(requestBody), 'muteHttpExceptions': true // 捕获错误响应,便于调试 }; let response = UrlFetchApp.fetch(url, requestOptions); let statusCode = response.getResponseCode(); // 根据状态码处理响应 if (statusCode === 204) { console.log("用户设置更新成功"); } else if (statusCode >= 200 && statusCode < 300) { let user = JSON.parse(response.getContentText()); console.log(user); } else { console.log("请求失败,状态码:" + statusCode); console.log("错误详情:" + response.getContentText()); } }
关键修改点
- 处理空响应体:新增状态码判断,当返回204时直接提示成功,跳过JSON解析。
- 编码用户邮箱:用
encodeURIComponent()处理邮箱,避免特殊字符(如@)导致URL格式错误。 - 添加调试配置:
muteHttpExceptions: true可以捕获错误状态码的响应内容,方便排查问题。 - 明确请求头:添加
Accept: application/json,确保服务器返回预期格式的响应。
内容的提问来源于stack exchange,提问作者winter9388
相关产品推荐
相关产品推荐

