Unlocking request header field access-control-allow-origin on VueJS

When attempting to send a POST request to the Slack API using raw JSON, I encountered the following error:

Access to XMLHttpRequest at '' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

Here is the code snippet:

const params =       {
                    "attachments":[
                      {
                        "fallback":"New Project Lead:<" + this.our_website + "|Click here to view>",
                        "pretext":"New Project Lead:<" + this.our_website + "|Click here to view>",
                        "color":"#D00000",
                        "fields":[
                          {
                            "title":"Company",
                            "value":this.user_company,
                            "short":false
                          },
                          {
                            "title":"Country",
                            "value":getName(this.user_country),
                            "short":false
                          }

                        ]
                      }
                    ]
                  };


                    this.axios.post('https://hooks.slack.com/services/continuation/of/url', params, {
                      headers: {
                        'content-type': 'application/json',
                        'Access-Control-Allow-Origin' : '*',
                      },
                    }).then((response)=>{
                        loader.hide();
                        let msg = "Sent Successfully";
                        this.displayAlert("Done", msg, "success");
                        setTimeout(() => {  // redirect to home after 2s
                            document.location = '/';
                        }, 2000);
                    }).catch((error) =>{
                        alert(error);
                    });
                }).catch((error) => {
                    loader.hide();
                    let msg = "Error : " + error;
                    this.displayAlert("Error", msg, "error");
                });

I am utilizing VueJS alongside the Axios HTTP library for this operation. Interestingly, when testing with POSTMAN, everything functions as expected.

Answer №1

It is not recommended to send this request directly from the frontend as many services block it for security reasons.

To work around this, you can create a backend sub service that will send the request to the Slack API on behalf of your frontend. This way, you will have your own custom service with a URL like mydomain.com/services/continuation/of/url. When this URL is called, your service will make a call to and return the Slack response.

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

Stuffing a container with an image without considering the proportions

I am experimenting with filling a parent <div> with an image without concern for proportions. Despite knowing that it may not look great at all sizes, I just want to test its feasibility. Currently, the image is scaling instead of stretching to fit m ...

Error message "Error: listen EADDRINUSE" is reported by node.js when calling child_process.fork

Whenever the 'child_process.fork('./driver')' command is executed, an error occurs: Error: listen EADDRINUSE at exports._errnoException (util.js:746:11) at Agent.Server._listen2 (net.js:1156:14) at listen (net.js:1182:10) ...

Leveraging JavaScript for Validating Radio Buttons

I've been following a tutorial guide on this specific website , but I'm encountering some difficulties despite following the exact steps outlined. Can someone provide guidance? Here is what I have done: <html> <script> fu ...

Is there an easy method for sorting through JSON data with various criteria?

After receiving a response from my web service containing an array of objects, I am looking to filter the data based on various combinations of values. What is the most efficient way to do this without impacting the performance of my web service? Data: Th ...

When using sequential jQuery 'pages', an error referencing the third frame occurs

I am new to using javascript/jquery and have been experimenting with the w3schools tutorials and jquery documentation. I created a page where user input is accepted and javascript prints output based on that input. I tried modifying it to work sequentially ...

What steps should I take to modify my database while utilizing radio buttons in the edit mode?

I am experiencing an issue with the radio button functionality. When creating a new user.jsp, I am able to successfully add the value from the radio button to the database. However, when I attempt to edit the values in the jsp, the changes do not reflect i ...

How can I efficiently iterate through the array of index IDs and then iterate individually through the communes, categories, and locations?

Currently, I am developing a nodejs typescript API where I am retrieving an array of objects using a map loop. The data for "communes", "category", and "location" is fetched from another API function based on the issuerId. However, I am facing issues with ...

Having issues with the grid system in a Vuetify v-footer component

I am struggling to organize my links into three columns in the footer along with the copyright line below. However, I am facing an issue where the copyright text appears in a mysterious fourth column, overlapping the third if the screen width is too small. ...

Encountering the error message "Angular 'undefined is not a function' when trying to define a component

My Ionic code was originally working fine, allowing the user to input a list. I decided to refactor it into a component for re-usability but encountered an error undefined is not a function on line 4 of the Javascript file. How can this issue be resolved? ...

The dynamic Vue.js transitions and effects are like a magic

I am using a v-for to render multiple child components: <div v-for="(pass) in scoringPass" :key="pass.decision"> <Pass :pass="pass"/> </div> Each of these child components contains a transition tag: &l ...

I am eager to retrieve every single item within the categories section utilizing a Vue component

Below is my Vue component CreateProduct.vue <template> <div> <div class="row mb-4"> <label for="category" class="col-md-4 col-form-label text-md-end">Category</label> ...

Customize bar chart colors in Vue ChartKick

When using a vertical bar chart, I am trying to assign different colors to each bar: Main.js import Chartkick from 'vue-chartkick'; import Chart from 'chart.js'; Vue.use(Chartkick.use(Chart)); File.vue <column-chart :data="chartD ...

What is the best way to modify an object within a pure function in JavaScript?

Currently, I am exploring different strategies to ensure that a function remains pure while depending on object updates. Would creating a deep copy be the only solution? I understand that questions regarding object copying are quite common here. However, ...

Use jQuery to set the onclick attribute for all elements rather than relying on inline JavaScript

I am currently facing a challenge with converting inline JS to jQuery. My goal is to eliminate all inline onclick events and instead target them by class. HTML - checkbox <td class="center"> <?php if ($product['selected']) { ?> ...

Unforeseen alterations in value occur in JavaScript when converting to JSON format

Having trouble generating a gantt chart from a JSON string, specifically with parsing the JSON string into a JSON object. I have a variable myString containing a JSON string that looks like this: {"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, { ...

The controller in my template is not being passed by the $routeProvider

I attempted to dynamically load a template in Angular using ngRoute... However, I encountered an issue with the following code: (app.js route configuration) app.config(function($routeProvider) { $routeProvider.when("/password", { templateUrl ...

The server is failing to provide the requested data in JSON format

I am struggling with making a simple API call using Node.js as the backend and React in the frontend. My Node.js file is not returning data in JSON format, and I'm unsure of the reason behind this issue. I need assistance with two main things: Why is ...

Ways to adjust timestamps (DayJs) by increments of 1 minute, 5 minutes, 15 minutes, 30 minutes, and more

Currently, I am exploring time functionality within React Native by utilizing DayJs. I have noticed a slight inconsistency when comparing 2 different points in time to calculate the time difference. Typically, everything works smoothly such as with 10:00 ...

A step-by-step guide on implementing ng-annotate to your code

Is there a way to run ng-annotate through the command line? I am attempting to combine and minify Angular, Angular Routes, and my own script.js into one file. When I use grunt uglify:app1, I encounter an injection error. While my code successfully minifies ...

Creating an inverted curve or border-radius for a div element is a design technique that can add

I've been tackling a project that requires me to style the border of a div in an inverted manner. To achieve this, I'm limited to using only CSS and JS without any plugins. I've searched through various online resources and similar questions ...