Axios获取Twilio频道数据修改后发起POST请求失败问题求助
Twilio频道更新请求问题修复方案
现有代码核心问题
postChannel函数未返回axios的Promise实例,异步请求脱离当前Promise链管控,会出现请求未完成就被回收、错误无法被外层捕获的问题,是POST请求看似没触发的核心原因- POST提交的
data格式错误,你将修改后的对象包裹在{json}中,Twilio API无法识别嵌套的参数 - Twilio Chat v2 API要求更新请求的参数格式为
application/x-www-form-urlencoded,直接提交JSON对象会被接口拒绝 - 如果你在浏览器前端环境运行该代码,直接携带账户密钥请求Twilio API会触发CORS限制,同时存在密钥泄露的严重安全风险,这类请求建议放在后端服务执行
修正后的代码
// 同步修改逻辑无需额外封装Promise function modifyChannel(sid, json) { console.log(json); const newAttributes = JSON.parse(json.attributes); newAttributes.task_sid = null; json.attributes = JSON.stringify(newAttributes); return json; } function postChannel(sid, json) { // 必须返回axios的Promise实例,纳入链式调用管控 return axios({ method: 'post', url: `https://chat.twilio.com/v2/Services/${DEV_CREDENTIAL.programmableChatSid}/Channels/${sid}`, auth: { username: DEV_CREDENTIAL.account, password: DEV_CREDENTIAL.token }, // 转换为x-www-form-urlencoded格式,直接传要更新的字段,不要嵌套json data: new URLSearchParams(json).toString(), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); } axios({ method: 'get', url: `https://chat.twilio.com/v2/Services/${DEV_CREDENTIAL.programmableChatSid}/Channels/${channel_sid}`, auth: { username: DEV_CREDENTIAL.account, password: DEV_CREDENTIAL.token } }) .then(response => modifyChannel(channel_sid, response.data)) // 调用postChannel必须return,才能把异步请求接入Promise链 .then(jsonModified => postChannel(channel_sid, jsonModified)) .then(postRes => console.log('更新成功', postRes.data)) .catch(err => console.log('请求出错', err));
额外注意事项
如果是Node.js后端环境运行上述代码可以直接生效,如果是前端浏览器环境,请将Twilio相关请求迁移到后端服务,避免密钥泄露和CORS问题。
内容的提问来源于stack exchange,提问作者Mauro Rivero
相关产品推荐
相关产品推荐

