skip to Main Content

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


  1. Chosen as BEST ANSWER

    Working code:

    const params = new URLSearchParams();
    
    params.append('Body','Hello from vcs');
    params.append('To',toNumber);
    params.append('From',fromNumber);
    
    exports.axios = () => axios.post(
      `https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
      params,
      {
        auth: {
          username: accountSID,
          password: authToken,
        },
      },
    ).then((res) => {
      console.log(res, 'res');
    }).catch((err) => {
      console.log(err);
    });
    

  2. Headers is actually a field of config, try something like this:

    const config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
        Authorization: `Basic ${accountSID}:${authToken}`,
      }
    }
    
    axios.post(URL, data, config).then(...)
    
    Login or Signup to reply.
  3. Or this (general example calling a Twilio endpoint)

    const axios = require('axios');
    
    const roomSID = 'RM1...';
    const participantSID = 'PA8...';
    
    
    const ACCOUNT_SID = process.env.ACCOUNT_SID;
    const AUTH_TOKEN = process.env.AUTH_TOKEN;
    
     const URL = "https://insights.twilio.com/v1/Video/Rooms/"+roomSID+"/Participants/"+participantSID;
        axios({
          method: 'get',
          url: URL,
          auth: {
            username: ACCOUNT_SID,
            password: AUTH_TOKEN
          }
        })
          .then((response) => {
            console.log(response.data);
          })
          .catch((error) => {
              console.log(error);
          });
    
    Login or Signup to reply.
  4. Axios makes an auth option available that takes an object with username and password options. You can use this with the username set to your account SID and password 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:

    const params = new URLSearchParams();
    params.append('Body','Hello from vcs');
    params.append('To',toNumber);
    params.append('From',fromNumber);
    
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
    };
    
    exports.axios = () => axios.post(
      `https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
      params,
      { 
        headers,
        auth: {
          username: accountSID,
          password: authToken
        }
      }
    }).then((res) => {
      console.log(res, 'res');
    }).catch((err) => {
      console.log(err);
    });
    
    Login or Signup to reply.
  5. The previous solutions did not work for me. I encountered either the Can't find variable: btoa error or A 'To' phone number is required..

    Using qs worked for me:

    import qs from 'qs';
    import axios from 'axios';
    
    const TWILIO_ACCOUNT_SID = ""
    const TWILIO_AUTH_TOKEN = ""
    const FROM = ""
    const TO = ""
    
    const sendText = async (message: string) => {
      try {
        const result = await axios.post(
          `https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Messages.json`,
          qs.stringify({
            Body: message,
            To: TO,
            From: FROM,
          }),
          {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
            },
            auth: {
              username: TWILIO_ACCOUNT_SID,
              password: TWILIO_AUTH_TOKEN,
            },
          },
        );
        console.log({result});
      } catch (e) {
        console.log({e});
        console.log({e: e.response?.data});
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search