Troubleshooting CORS Problem in VUE JS 3 while Making API Request from Localhost to External API服务

I've been dealing with a CORS issue for quite some time now. I've tried all the solutions on Stack Overflow, but nothing seems to be working for me. Can anyone help me figure out what's wrong with my code? I'm using VUE JS 3 and trying to access an API hosted on a different server. Despite trying various headers, none of them have helped me resolve the issue.

ENV URL

 VITE_APP_API_URL="http://localhost:5173" 

The vue.config.js file is located in the root folder:

module.exports = {
     devServer: {
            proxy: 'https://ded.austory.it'
           }
    }

Here's how I'm calling the API:

function login(credentials: User) {
     // ApiService.setCrossHeaders();
    return ApiService.post("/login", credentials)
      .then(({ data }) => {
        setAuth(data);
      })
      .catch(({ response }) => {
        setError(response.data.errors);
      });
  }

Definition of the API Service:

 .......
import type { AxiosResponse } from "axios";
import axios from "axios";
import VueAxios from "vue-axios";
  .....

/**
   * @description set the POST HTTP request
   * @param resource: string
   * @param params: AxiosRequestConfig
   * @returns Promise<AxiosResponse>
   */
  public static post(resource: string, params: any): Promise<AxiosResponse> {
    return ApiService.vueInstance.axios.post(`${resource}`, params);
  }

The above code handles the API calls, but I still can't figure out what's causing the issue. The current output is

https://i.sstatic.net/kff0Sab8.png

When I change the ENV variable to:

https://i.sstatic.net/AJWLp6Q8.png

https://i.sstatic.net/oTiQwMrA.png

Interestingly, when setting the ENV URL to:

   VITE_APP_API_URL="https://preview.keenthemes.com/metronic8/laravel/api" 

the CORS error disappears. How is this possible when there are no other references to this URL in my project?

Answer №1

After discussing the issue with my network team at work, we were able to resolve the problem on the destination server. The server configuration was updated, allowing any host to send requests to access data from the API. Our project was hosted on abc.com server while we were retrieving data from xyz.com server, both of which belonged to our company. With the necessary updates, we were granted permission for abc.com to communicate with xyz.com, resolving the issue.

In terms of Front-end UI development, I utilize Vue JS and partially Vite. Initially, I had configured proxy settings in vue.config.js based on @estus-flask's guidance. However, it was later determined that these configurations should have been made in vite.config.js as per @estus-flask's advice. Despite trying various configurations, the issue persisted. For more information on configuring vite.config.js for proxy settings, refer to the vite documentation.

.....
server: {
        proxy: {
            '/foo': 'http://localhost:4567',
            '/api': {
                target: 'http://jsonplaceholder.typicode.com',
                changeOrigin: true,
                secure: false,
            },
        },
    },
.....

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

How to update agGrid after changing checkbox value

I've encountered an issue with the agGrid component where I'm trying to display checkboxes within a cell. I attempted to add an extra checkbox for selecting all checkboxes in the table, but it's not functioning as expected. Even when all che ...

Choosing the primary camera on a web application with multiple rear cameras using WebRTC

Having a bit of trouble developing a web app that can capture images from the browser's back camera. The challenge lies in identifying which camera is the main one in a multi-camera setup. The issue we're running into is that each manufacturer u ...

Transitioning classes in Vue elements

Is it achievable to create a smooth transition between two CSS classes with different background images? That's the challenge I'm currently facing. Here is the Vue code snippet I am working on: <div id="flip-list-demo" class="demo"> & ...

Integrating a conditional statement into the existing for loop code to conceal the covers

My goal is to hide the covers after they are clicked using an if statement within the for loop code. I believe this is where it should be placed. Trying to prevent this action from happening. https://i.sstatic.net/eLSto.png I made an attempt at achievin ...

There is no index signature in AxiosStatic

As I convert a hook from JavaScript to TypeScript, I encounter the following error: (alias) const axios: AxiosStatic import axios Element implicitly has an 'any' type because type 'AxiosStatic' has no index signature. Did you mean to ca ...

How can I pass an object into EJS templates from views in Express 3.x?

Currently, I am utilizing ejs templates in combination with node.js and express 3.x. Is there a way to display the data object that is passed into the view? Can it be achieved similar to this example in index.ejs: <%= dump(session) %> ...

Generating Bootstrap carousel items dynamically using JavaScript

One of my recent achievements includes creating a webpage that displays a list of loaded data, some of which contain YouTube links. I am currently facing a challenge in trying to showcase these videos in a bootstrap carousel due to the complexity of integ ...

Ensuring a radio button is pre-selected by default in React by passing in a prop

Assume I have a React function similar to this function Stars({handleStarClick, starClicked}) { if (starClicked === 3) { document.getElementById('star3').checked = true } return ( <div className="rate"> ...

Localization support is working partially in a Node Express application that uses Handlebars for templating

Whenever I visit a URL with the ?lang=en query parameter, the English translation is never used. However, the Hungarian text changes work perfectly fine, displaying text to test on Hungarian in the default "hu" language without any issues. What could be ca ...

Retrieve an array of items from the Firebase snapshot

Currently in the process of retrieving items from my Firebase database, I am utilizing a snapshot that is generated when the page loads. I have collected the values of each object in an array and I am now attempting to add an item from each object into a s ...

When an HTML input button within a table fails to trigger any jQuery function upon being clicked

I currently have a table set up with multiple rows and columns. <table style="width: 100%;" class='table_result'> <tr><td>Text</td><td>Text</td><td>Text</td><td>Text</td> ...

Could Object attributes be incorporated into C#?

When working with JavaScript, it's pretty straightforward to create a new object and set its attributes. For example, if I want to set an attribute of an object, I can simply do `objectName.attributeName = whatever`. However, is there a way to achieve ...

Step-by-step guide to configuring preact-render-to-string with Express

Could someone guide me through setting up preact-render-to-string with express? Detailed instructions are here Installation for express can be found here I've gone through the provided links, but I'm unfamiliar with using node. I'm struggl ...

Explaining the jQuery $.post method

After a thorough search, I finally discovered the importance of adding return false; at the end of my JQuery code for posting data. Without it, my code wasn't functioning as expected. As a beginner in JQuery, I would appreciate some insights into the ...

Issue in PHP / MySQL: Only the most recent ID is deleted during multiple deletions

I've encountered an issue with my code regarding deleting multiple data from a MySQL database that is populated from a Select Option. For example, when I select data with ids 5, 2, and 4, and then press the delete button, only the latest id (5) gets ...

Creating an Engaging Data Visualization: Blending Candlestick Insights with Line Graphs

I'm attempting to display a moving average on a candlestick chart, but I'm facing an issue where the path of the line is not fully appearing on the SVG canvas that I've created. I've searched through various posts to understand how to o ...

I am interested in excluding the seconds and milliseconds from my date and time

I currently display my time in the following format: 5:34 PM I only want to show the hour and minute. How can I achieve this? ...

When selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...

How can I reset the search input in v-autocomplete (multiple) after selecting a checkbox from the drop-down menu?

I am facing an issue with the v-autocomplete component from Vuetify. Currently, when I enter "Cali" in the search input and select "California" from the dropdown list, the "Cali" value remains in the search input field. I need the entered value to be clear ...

Is there a way to temporarily hide content hidden with ng-hide from being displayed on the page?

Recently delving into the world of Angular, I've come across an issue where an element appears briefly on the page before disappearing. My goal is to prevent this behavior, but I am unsure how to go about it. The specific scenario involves a radio bu ...