Handling CORS in Vue.js applications

As a newcomer to Vue, I am currently grappling with a CORS issue in my application. During development at http://localhost:8080/, sending a request to , I was able to resolve the CORS problem using the following code snippet:

vue.config.js

module.exports = {
  devServer: {
    proxy: "http://zz.zz.zz.zz:3000/"
  }
};

However, when my app is in production mode at http://zz.zz.zz.zz:3001/, attempting to send a request to results in a CORS error. I tried the code below but saw no improvement. What could be going wrong?

.env.production & .env.development

VUE_APP_API_URL=http://zz.zz.zz.zz:3000/

An example of a request in a component:

let url = process.env.VUE_APP_API_URL + "?name=anna";
let formData = new FormData();
formData.append("file", this.file);
const config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
};
axios
  .post(url, formData, config)
  .then(...)
  .catch(...)

(CORS are allowed on the server)

Here's package.json:

{
  "name": "PROJECT_1",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.20.0",
    "core-js": "^3.6.5",
    "vue": "^2.6.11",
    "vue-cookies": "^1.7.4",
    "vue-plugin-load-script": "^1.3.2",
    "vue-router": "^3.2.0",
    "vuex": "^3.4.0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/eslint-config-prettier": "^6.0.0",
    "babel-eslint": "^10.1.0",
    ...
}

Answer №1

If you encounter a CORS error, it indicates that the CORS is not enabled or misconfigured on your backend server. => Make sure to enable CORS on your backend so that it can send back the necessary CORS headers in the response.

Verify the headers of your backend responses to confirm that CORS is correctly set up, like this:

Answer №2

Check out the vue-axios-cors package for integrating Axios with Vue.

import Vue from 'vue'
import AxiosPlugin from 'vue-axios-cors';

Vue.use(AxiosPlugin)

Now, you can seamlessly use axios in your Vue project just like you normally would.

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 can be done to ensure that the value from a promise is retained and available for use in

Currently, I am executing a database query and then manipulating the data to obtain a single numeric value. This value is essential for use in a subsequent array. The current definition of the array appears as follows (see below). The issue at hand is tha ...

Issues encountered when attempting to append the array objects to HTML using $.getjson

Hello, I have a JSON data structure as shown below: [{ "menu": "File", }, { "menu": "File1", }] I have created jQuery code to dynamically add the response to my HTML page like this: $(document).ready(function () { $.getJSON('data.json&a ...

Attempting to connect information to state using an input field that is being iterated over in React

Struggling with binding state values to input values using an onChange function handleChange = event => { this.setState({ [event.target.name]: event.target.value }); }; The issue arises when the Input fields are within a map and assi ...

Testing a service resolution in a controller through unit testing

As I attempt to create a test for my home module, I keep encountering an error that reads "unknown provider: service." Interestingly, when I modify resolveSomething in my home module to output a string, the app functions as expected, indicating that the re ...

Switch up the CSS variable within an embedded iframe

I'm in a predicament with a specific issue. I am currently utilizing Angular to incorporate an Iframe. Let's imagine the angular app as A and the Iframe as B. B is being loaded within A. Within B, I have utilized CSS variables to define colors. I ...

Guide to setting the hiddenfield value within a listview using javascript or jquery

Here is the javascript code that I am using to retrieve the value from my textbox with autocompleteextender. <script type="text/javascript"> function txt_lect_in_AutoCompleteExtender_itemSelected(sender, e) { var hdEmpId = $get('& ...

Converting blobs to strings and vice versa in Javascript

After successfully converting a blob to a string using FileReader, the challenge now is to convert it back: var reader = new window.FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { base64data = reader.result; var blobToSend ...

Tips for setting up a scheduled event on your Discord server using Node.js

Hello fellow programmers! Recently, I've been working on a Discord bot using discordjs sdk. I'm trying to implement a feature where the bot creates an event every week. I went through the discordjs guide and checked the discord api documentati ...

The `mouseenter` event handler fails to trigger properly on its initial invocation

As I work on a function to remove a CSS class display:hidden; when the mouse enters a specific part of the DOM to reveal a menu, I encounter an issue. Upon loading the page and hovering over the designated area for the first time, the event fails to trigge ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

detect mouse click coordinates within an iframe that spans multiple domains

I am currently encountering an issue with tracking click position over a cross-domain iframe. Here is my current code: <div class="poin"> <iframe width="640" height="360" src="http://cross_domain" frameborder="0" allowfullscreen id="video">< ...

The implementation of an onclick event in a freshly created HTML element is functioning solely on the final element

One issue I encountered was that when I generated page number buttons at the bottom of a page, the onclick event only worked with the last button created. Below is an example of how the page buttons were displayed: https://i.stack.imgur.com/wHwI0.png ...

Ways to modify the appearance of the button within ion-calendar

Looking to customize the styling of ion-calendar classes Attempting to add styles to the ion-calendar-month class, but not seeing any changes take effect. ...

Persist the data retrieved from an asynchronous function in the memory

I am faced with a challenge in Node.js where I need to store an object in memory. This particular object is created asynchronously from an API call. The issue at hand is that previously, this object was synchronous and many parts of the application were de ...

Can custom HTML elements be designed to function similarly to standard ones?

What is the best way to create a custom HTML element that functions as a link without relying on inline Javascript? For instance: <x-button href="...">...</x-button> Can I develop an element like <x-button> that can accept an attribute ...

Is it possible for node-java to accept anonymous functions as parameters in Java?

I am looking to pass an anonymous function from JavaScript to Java using node-java (https://github.com/joeferner/node-java). Below is a snippet of the Java code for reference: public class Example { public Example() { } public interface Callb ...

What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks. Everything is functioning smoot ...

Difficulty with formatting decimal points in JavaScript

I seem to be having an issue with decimal places in my code. Currently, it's showing the result as 123 123 12 but I actually need it to be displayed as 12 312 312. Is there anyone who can assist me with formatting this correctly? Here is the section ...

Exploring the context of file upload events and analyzing javascript functionality

Can you help me conditionally trigger the file upload dialog using JavaScript based on an Ajax response? <input type="file" id="Upload"> I have hidden the input element as I don't want to display the default file upload button. Instead, ther ...

Tips for adjusting the horizontal position of a grid item within a map() loop

I am trying to align the text in my Timeline component from Material Ui always towards the center of the timeline. The TimelineContent contains Paper, Typography (for title and description), and an image. Currently, I have multiple TimelineContent element ...