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

What could be the reason for my post jQuery Ajax request sending JSON data?

After downloading some code, I came across the following fragment: function FetchCommentsBySessionIDWCF_JSON() { varType = "POST"; varUrl = "service/CommentSessionIDWCFService.svc/FetchCommentsByPost"; varData = ' ...

Handle all link clicks on the webpage

My challenge is that some users are required to utilize a virtual desktop in order to access specific information on my website. However, within the virtual environment, there are links leading to external content that do not function properly. I am seekin ...

I need assistance on updating a document in MongoDB using Node.js

I'm in the process of developing a feature that automatically updates a player's high score to their account when they achieve a new record. However, I'm struggling with how to search for a player by name and update their tag using mongoose. ...

Getting the present location on Google Maps for the web: A step-by-step guide

As a newcomer to this API, I have successfully generated an API key but am unsure of how to implement Google Maps. Despite my extensive research, I have been unable to find a solution that works for me. I am seeking assistance in locating users or devices ...

Is it feasible to commit an object on Vue X through Actions?

I have a question regarding Vue X and actions (with commit). Can an object be passed as input in Commit? Similar to: ... action{ ResetLoginStats({commit}){ commit({ 'SetMutation1':false, 'SetMutation2':true, &a ...

Flask does not provide a direct boolean value for checkboxes

After struggling for a week, I am still lost on where to make changes in my code. I need the checkbox to return a boolean value in my Flask application. Below are snippets of the relevant code: mycode.py import os, sqlite3 from flask import Flask, flash ...

Accessing the selected value from a dropdown list filled with data from a PHP array in HTML

My HTML and PHP code consists of a select dropdown that looks like this: <select name="category" id="_category" class="_cateogry" onchange="submitTheForm() > option value="">Please select</option> <?php foreach ($categories as $cont ...

Using Javascript to delete an HTML list

Currently, I am working on a webpage that includes notifications along with options to mark them as read individually or all at once. However, when attempting to use my loop function to mark all notifications as read, I noticed an issue. let markAllAsRead ...

When JQuery is written in a separate file, it does not get applied in the HTML file

I've encountered an issue that seems to have similarities to others, but despite trying various solutions and writing JQuery code in a JS file, I can't seem to get it to work properly. When I include the path for the JS and JQuery version in the ...

Setting up the CSS loader in a Vue.js project using webpack

I am currently working on a new vue-cli project and have successfully installed the Pure.CSS framework using npm install purecss --save. However, I am struggling to seamlessly integrate, import, or load the css framework into my project. I am unsure of whe ...

Vue alert: Issue encountered in watcher 'childItems' callback - 'TypeError: Unable to access property 'tag' as it is undefined'

I am currently in the process of developing the Store page for a web application. I am utilizing Axios to retrieve product data and display it in a Vue template. While the backend functionality is working correctly and the frontend is rendering successfull ...

Show singular array element upon click

I need help with a specific task. When a button is clicked, I want to display a random item from an array. Each array item should only be displayed once. Currently, my code is set up as follows: When the button is clicked, a random array item is displ ...

Passing data between Vue child components

I'm currently dealing with a structure like this: <Root> <HomeNav> router-view <RouterLink> <RouterLink> <RouterLink> <RouterLink> <RouterLink> <Home> router-view <RouterLink> Each of the HomeNav ...

The JavaScript codebase is dragging its feet in responding

In my Node and React (NextJS) SSR project, I have integrated the createjs library for JavaScript animations. However, since there is no NPM package available, I had to download the minified JS library and host it locally. After adding this library to the ...

Can we programmatically switch to a different mat-tab that is currently active?

Looking to programmatically change the selected mat-tab in a TypeScript file. I came across a solution for md-tab, but I need it for mat-tab. I attempted the suggested solution without success. Here's what I tried: HTML <button class="btn btn- ...

Toggle visibility of table row upon user click (HTML/JQuery)

Having an issue with showing or hiding table rows using jQuery. I would like it so that when a user clicks on a table row with id="jobtitle", the corresponding tr with class="texter" will either show up or hide if it is already displayed. This is my curre ...

Select the even-numbered occurrences of a specific class in CSS using the nth-child()

I am encountering an issue with my table layout. The structure is similar to the following: <tbody> <tr class="row">...</tr> <tr class="row--expanded">...</tr> <tr class="row">...</ ...

Refreshing data and manipulating arrays using AngularJS

Currently, I am developing an application utilizing AngularJS and LocalStorage. I've encountered a challenge that seems a bit too intricate for me to handle. The app involves managing lists of people with the ability to add arrays of names. The proce ...

The Uib-Dropdown functionality is not functioning properly when placed within the body of an HTML view

After correctly installing the following dependencies: "ui-bootstrap": "0.12.2", "ngAnimate": "1.5.5", "AngularJs": "1.5.5 I encountered an issue with creating a dropdown menu in my HTML view. Despite no visible errors and successful implementati ...

Tips for accessing child elements within an Angular component

I'm struggling to get a reference of child elements within a component. I have experimented with ElementRef, TemplateRef, QueryList, ViewChild, ViewChildren, ContentChild, and ContentChildren without success. <app-modal> <section #referenc ...