Node.js中使用Axios向Twilio发送POST请求遭遇认证错误
解决Twilio Axios请求的"Authentication Error - No credentials provided"问题
你的代码存在三个关键问题,导致认证失败,逐一修正即可解决:
- Axios参数结构错误:
axios.post的第三个参数必须是配置对象,你直接传入了headers对象,导致Axios无法正确识别认证头信息。 - Basic认证格式错误:Twilio要求将
AccountSID:AuthToken做Base64编码后,再拼接Basic前缀,你直接拼接了原始字符串,未做编码处理。 - 请求体格式不匹配:Twilio需要
application/x-www-form-urlencoded格式的请求体,但你直接传入了JS对象(Axios默认会转为JSON),还错误地将Content-Type放在了请求体内。
修正后的完整代码
先确保安装qs模块(用于转换请求体格式):
npm install qs
然后替换你的代码:
const qs = require('qs'); const axios = require('axios'); // 请替换为你的实际参数 const accountSID = '你的Twilio账户SID'; const authToken = '你的Twilio认证Token'; const toNumber = '目标手机号'; const fromNumber = '你的Twilio手机号'; // 正确生成Basic认证头 const authHeader = `Basic ${Buffer.from(`${accountSID}:${authToken}`).toString('base64')}`; const headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', Authorization: authHeader, }; const body = { Body: 'hi from vsc', To: toNumber, From: fromNumber, }; exports.axios = () => axios.post( `https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`, qs.stringify(body), // 将对象转为urlencoded格式 { headers } // 第三个参数是包含headers的配置对象 ).then((res) => { console.log(res, 'res'); }).catch((err) => { // 打印更详细的错误信息 console.log(err.response?.data || err.message); });
替代方案(无需qs模块)
如果不想安装额外模块,可以用URLSearchParams处理请求体:
const body = new URLSearchParams({ Body: 'hi from vsc', To: toNumber, From: fromNumber, });
额外排查建议
- 确认
accountSID和authToken没有拼写错误,且权限正确。 - 若仍有问题,在catch中打印
err.response.data,Twilio会返回具体的认证失败原因。
内容的提问来源于stack exchange,提问作者heyooo12
相关产品推荐
相关产品推荐

