in Node.js, I am trying to send a POST request with Axios to Twilio and send an SMS message to my phone. But I am getting an ‘error: Authentication Error – No credentials provided ? Here is the code:
const body = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Body: 'hi from vsc',
To: toNumber,
From: fromNumber,
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
};
exports.axios = () => axios.post(`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`, body, headers).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
I also tried to use the same parameters with POSTMAN and the POST request is successful. I also tried to encode my authorization username and password to Base 64, but with no success.
I wrote to Twilio customer help but haven`t received any replies yet.
5
Answers
Working code:
Headers is actually a field of config, try something like this:
Or this (general example calling a Twilio endpoint)
Axios makes an
auth
option available that takes an object withusername
andpassword
options. You can use this with theusername
set to your account SID andpassword
set to your auth token.The headers object should be sent as the headers parameter of a config object in the third parameter to
axios.post
. Like so:The previous solutions did not work for me. I encountered either the
Can't find variable: btoa
error orA 'To' phone number is required.
.Using
qs
worked for me: