如何通过JavaScript获取Fetch API响应状态及Twilio短信SID
解决Twilio API调用的两个问题
问题1:无法获取响应状态(返回undefined)
原因
fetch 是异步方法,返回的是Promise对象,而非直接的Response实例。直接访问 response.status 时,Promise还未完成,因此得到undefined。
解决方案
使用 await(需在async函数中)或 .then() 方法等待Promise resolve,获取实际的Response对象:
方式1:使用await(推荐)
// 确保代码在async函数内 async function sendSMS() { const response = await fetch('https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + btoa('$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN') }, body: 'Body=Hi there, this is a test message from cURL&From=$TWILIO_NUMBER&To=$TO_NUMBER' }); console.log('response.status: ', response.status); } sendSMS();
方式2:使用.then()
fetch('https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + btoa('$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN') }, body: 'Body=Hi there, this is a test message from cURL&From=$TWILIO_NUMBER&To=$TO_NUMBER' }).then(response => { console.log('response.status: ', response.status); });
问题2:无法从XML响应中获取短信SID
原因
response.text() 返回的是XML格式的字符串,不是JavaScript对象,因此无法通过 .Sid 直接访问属性。
解决方案
有两种处理方式:
方式1:解析XML字符串
使用浏览器内置的 DOMParser 解析XML,再通过DOM查询提取Sid:
async function sendSMS() { const response = await fetch('https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + btoa('$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN') }, body: 'Body=Hi there, this is a test message from cURL&From=$TWILIO_NUMBER&To=$TO_NUMBER' }); const xmlString = await response.text(); const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); const smsSid = xmlDoc.querySelector('Sid').textContent; console.log('短信SID: ', smsSid); } sendSMS();
方式2:请求JSON格式响应(更简便)
向Twilio请求返回JSON格式,只需在请求头中添加 Accept: application/json,之后直接用 response.json() 获取对象:
async function sendSMS() { const response = await fetch('https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + btoa('$TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN'), 'Accept': 'application/json' // 新增此请求头 }, body: 'Body=Hi there, this is a test message from cURL&From=$TWILIO_NUMBER&To=$TO_NUMBER' }); const result = await response.json(); console.log('response.status: ', response.status); console.log('短信SID: ', result.Sid); } sendSMS();
内容的提问来源于stack exchange,提问作者Nancy Moore
相关产品推荐
相关产品推荐

