I have been facing CORS issue form many days. I have applied all the solutions that are available in Stack Overflow, but nothing helpful for me. Can anyone tell me what is going wrong with my code? I am using VUE JS 3 where I am using an API that is hosted on a different server. I tried all headers that can fix but nothing was helpful for me.
ENV URL
VITE_APP_API_URL="http://localhost:5173"
vue.config.js: file is placed in root folder.
module.exports = {
devServer: {
proxy: 'https://ded.austory.it'
}
}
Calling API from here:
function login(credentials: User) {
// ApiService.setCrossHeaders();
return ApiService.post("/login", credentials)
.then(({ data }) => {
setAuth(data);
})
.catch(({ response }) => {
setError(response.data.errors);
});
}
Defining 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 is responsible for making an API call. So what is going wrong I do not know. output is
If I set in env : VITE_APP_API_URL=”https://ded.austory.it” (real site name can’t share here.) then
But there is a catch here, when setting ENV URL
VITE_APP_API_URL="https://preview.keenthemes.com/metronic8/laravel/api"
after this, No Cors error comes from the localhost. How I do not know? I checked in my project there is no other definition of this URL in a project. hHw it is accepting but mine not?
3
My problem was fixed by the target server ( destination server ). I discussed this issue with my network team in my company. they updated the server configuration. so after that, any host can send a request to get data from API.
In Detail, I want to say that my project was on the abc.com server and I was requesting data from the xyz.com server. both hosting was of our company. so that they allow me to request abc.com to xyz.com. we are using the services of xyz.com. so after updating this issue was fixed.
Another thing is that my Front-end UI is Vue JS where partially I am using vite. so for proxy, I was writing the code in vue.config.js that should be written on vite.config.js based on @estus-flask . So after that, it could not help me any more. I mentioned this code because @estus-flask mentioned that vue.config.js is not relevant. So @estus-flask bro I tried both configurations but nothing helpful..
For vite.config.js we can use a proxy … For More detail : visit vite doc
.....
server: {
proxy: {
'/foo': 'http://localhost:4567',
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
secure: false,
},
},
},
.....