本地号码拨打Twilio号码失败:Content-Type引发502错误
问题描述
使用本地号码拨打Twilio号码时,Webhook会向/place-call发送POST请求,但最终触发错误回退URL。Twilio提示无法处理目标URL的Content-Type,所有请求必须返回合法的Content-Type,未返回该类型的请求会在Debugger中显示为502 Bad Gateway错误。
错误日志
Twilio无法处理所提供URL的Content-Type。所有请求都必须返回合法的Content-Type,未返回该类型的请求会在Debugger中显示为502 Bad Gateway错误。
相关代码
place-call.js 文件
const callerNumber = '+1XXXXXXXXXX'; const callerId = 'client:alice'; const defaultIdentity = 'alice'; exports.handler = function (context, event, callback) { var url = 'https://' + context.DOMAIN_NAME + '/incoming'; const client = context.getTwilioClient(); var to = event.to; if (!to) { to = event.To; if (!to) { console.error("Could not find someone to call"); to = null; } } // console.log("To: " + JSON.stringify(event)); if (!to) { client.calls.create({ url: url, to: 'client:' + defaultIdentity, from: callerId, }, function (err, result) { // End our function if (err) { callback(err, null); } else { callback(null, result); } }); } else if (isNumber(to)) { console.log("Calling number:" + to); client.calls.create({ url: url, to: to, from: callerNumber, }, function (err, result) { // End our function if (err) { console.log("Error: " + err); callback(err, null); } else { callback(null, result); } }); } else { client.calls.create({ url: url, to: 'client:' + to, from: callerId, }, function (err, result) { // End our function if (err) { callback(err, null); } else { callback(null, result); } }); } }; function isNumber(to) { if (to.length == 1) { if (!isNaN(to)) { console.log("It is a 1 digit long number" + to); return true; } } else if (String(to).charAt(0) == '+') { number = to.substring(1); if (!isNaN(number)) { console.log("It is a number " + to); return true; }; } else { if (!isNaN(to)) { console.log("It is a number " + to); return true; } } console.log("not a number"); return false; }
incoming.js 文件
//'https://' + context.DOMAIN_NAME + '/incoming' exports.handler = function(context, event, callback) { const twiml = new Twilio.twiml.VoiceResponse(); twiml.say("Congratulations! You have received your first inbound call! Good bye."); callback(null, twiml.toString()); };
解决方案
问题根源在于incoming.js返回TwiML时未指定正确的Content-Type(text/xml),Twilio无法识别返回内容的类型,导致502错误。
修改incoming.js,返回包含响应头的对象,明确指定Content-Type:
exports.handler = function(context, event, callback) { const twiml = new Twilio.twiml.VoiceResponse(); twiml.say("Congratulations! You have received your first inbound call! Good bye."); callback(null, { headers: { 'Content-Type': 'text/xml' }, body: twiml.toString() }); };
修改后,Twilio就能正确解析返回的TwiML内容,解决502 Bad Gateway错误。
内容的提问来源于stack exchange,提问作者Syed Muzammil Ali
相关产品推荐
相关产品推荐

