Encountering a CORS Policy Issue while trying to make a POST request to the Twilio API

When I try to make a simple POST request from my VueJS application to the Twilio API for sending an SMS, I encounter an error message:

"Access to XMLHttpRequest at 'https://api.twilio.com/2010-04-01/Accounts/AC42exxxxxxxxxxcfa9c48/SMS/Messages' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field username is not allowed by Access-Control-Allow-Headers in preflight response."

The code causing this error is as follows:

sendTwilio(){
        const accountSid = process.env.TWILIO_ACCOUNT_SID;
        const authToken = process.env.TWILIO_AUTH_TOKEN;
        const sFromNumber = process.env.TWILIO_NUMBER;
        const sBaseURL = 'https://api.twilio.com';
        const phoneNumber = parsePhoneNumberFromString(this.sms.to_number,'US') 
    
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`,
            'username': `${accountSid}`
        },
    
        sBodyText='Test'
    
        this.SmsUrl = sBaseURL + '/2010-04-01/Accounts/' + accountSid + '/SMS/Messages';
    
        if (phoneNumber.isValid()){
            this.sms.formattedPhone = phoneNumber.number;
    
            this.postData = 'From=' + sFromNumber 
                            + '+To=' + phoneNumber.number 
                            + '+Body=' + sBodyText
    
            axios.post(`${this.SmsUrl}`, this.postData, {
                headers: headers
            })
            .then((response) => {
                console.log(response)   
            })
            .catch((error) => {
                console.log(error)   
            })                    
        }
    },
    

Do you think the issue lies with the username format in the header or could it be related to my CORS settings?

This is how my CORS settings are configured:

CORS_ORIGIN_ALLOW_ALL = True

    CORS_ORIGIN_WHITELIST = [        
        'http://localhost:8000',
        'http://localhost:8080',
        'http://127.0.0.1:8000'
    ]
    

Answer №1

When it comes to authentication, Twilio relies on Basic Auth. If you're using axios for a POST request, make sure to include the following code:

const headers = {
    'Content-Type': 'application/json'
};
const auth = {
    username: accountSid,
    password: authToken
}
[...]
axios.post(this.SmsUrl, this.postData, {
    auth: auth,
    headers: headers
})

It's important to note that exposing your Twilio credentials in a browser application is risky. Be cautious and refer to the question comments for more details.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving JSON data with Node.js

Receiving a JSON response from TMDB: { "id": 283350, "results": [ { "iso_3166_1": "BR", "release_dates": [ { "certification": "12", "iso_639_1": "pt", "note": "Streaming", "release_date": ...

Incorporate additional information into the current data series within Lightning Chart

In my React JS application, I have successfully used a point series to create a chart displaying data. However, I am now looking to bind real-time data to the chart. For example, when the chart initially loads with 10 points, I want to continuously receiv ...

Utilize jQuery and PHP to populate an HTML Select Field with data retrieved from a MySQL Database in JSON format

I am exploring how to Transfer Database Data into an HTML Dropdown Selection Field using jQuery. I came across a useful example that seems promising. Although I am new to jQuery and JavaScript, I am eager to learn. My goal is similar to the approach descr ...

Enable AJAX to dynamically load pages without caching

I am currently using an ajax function to refresh a specific division on a webpage with HTML content. <script> $('#scene_container').load('scene.html', function () { cache: false }); </script> ...

Leverage global functions when implementing Vue directives

Attempting to implement lodash methods (_.isEmpty) within Vue directives as shown below: <div class="post" v-for="post in posts"></div> ... <div class="comments" v-if="! _.isEmpty(post.comments)"> <div class="comment" v- ...

Differentiating programmatic from operational errors with the use of promise-based node.js programming: A comprehensive guide

Node.js is a new adventure for me and I'm really enjoying it. However, I'm struggling to grasp proper error handling techniques. While the internet offers plenty of resources on this topic, most of them focus on callback-based programming which ...

Discovering the scroll position in Reactjs

Utilizing reactjs, I am aiming to manage scroll behavior through the use of a `click` event. To start, I populated a list of posts using `componentDidMount`. Next, upon clicking on each post in the list using the `click event`, it will reveal the post de ...

The insertion was unsuccessful: Technique used in Meteor 1.3 and React

I am looking to add some simple text to the MongoDB using React. However, when I submit the form, the following error message is displayed in the console: insert failed: Method '/resolutions/insert' not found My setup includes autopublish and i ...

Can you outline the distinctions between React Native and React?

Recently delving into the world of React sparked my curiosity, leading me to wonder about the distinctions between React and React Native. Despite scouring Google for answers, I came up short on finding a comprehensive explanation. Both React and React N ...

Is JSDOM capable of configuring exuberant ctags for a project setup?

Anticipating great javascript ctags support got me considering the possibility of using a project like to configure ctags for optimum vim usage. ...

Is there a way to link the scrolling of two ag-grid data tables together for synchronized movement?

I have integrated ag-grid into my Angular project and I am looking to display two data tables (ag-grid) stacked on top of each other. Both data tables should scroll together, meaning when I scroll in table 1 or table 2, the content of both tables should m ...

Retrieving JSON data from outside the React root directory

My current project includes an older javascript/php application with numerous JSON files used to retrieve data from the database. As I plan to migrate some modules to React, I am wondering if it's possible to still fetch data from these JSON files wi ...

Tips for retrieving data for client components on the server side

When referring to Client Components, I am talking about files that use use client at the top, while Server Components are files that utilize use server accordingly. I haven't come across any mention of fetching data on the server side and directly pa ...

Using Ajax/jQuery in combination with Mongodb

My experience with Ajax/jQuery is fairly new. I am currently working on creating a sample HTML page using Ajax/jQuery to retrieve all customers and search for a customer by ID. Each customer has three variables: ID, firstName, and lastName. I am looking t ...

Issues with non-functional plugins that utilize AJAX functionality

I am encountering an issue with my code that includes an ajax script for deleting a record, along with an animation during the deletion process. However, when I try to integrate the ajax script with plugins for confirmation, it seems to not be working prop ...

AngularJS: Understanding the 'controller as' syntax and the importance of $watch

Is it possible to subscribe to property changes when using the controller as syntax? controller('TestCtrl', function ($scope) { this.name = 'Max'; this.changeName = function () { this.name = new Date(); } // not working ...

Error: script not found when starting deployment of nodejs on heroku

Trying to deploy a nodejs application on Heroku and have defined the start script in package.json "scripts": { "test": "./node_modules/.bin/mocha -r mocha-cakes", "start": "rm -r -f database/test.db && node app.js", "start-win": "del d ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...

The requested resource at http://127.0.0.1:8000/storage/profiles/ could not be located (Error 404: Not

I have successfully implemented a feature on my website that allows users to upload their avatar picture using Vue.js and Laravel as the backend. The image is stored in the storage directory, and I can display it on the user's profile page using Vue.j ...

Execute JavaScript function in NodeJS server background

I have developed a function that periodically monitors the battery statuses of connected android devices and returns an array. How can I execute this function on server startup and ensure it continues to run while sharing its information with other pages? ...