I'm using @vue/cli 3.x and in my vue.config.js I have this:
devServer: {
proxy: {
"/api": {
ws: true,
changeOrigin: true,
target: "http://localhost:8080"
}
}
}
But I keep getting CORS error:
Access to XMLHttpRequest at 'http://localhost:8080/api' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Any idea?
Use a Serverless Function. A more commonly used solution to resolve CORS error is to use a serverless function. It is an alternate way to proxy your requests, but instead of relying on a free third-party service, you can build your micro-infrastructure to call a web service and feed data to an API endpoint.
You can set a proxy in Vue using the vue. Not every fix for a CORS error is a good fix. For example, setting the value for the Access-Control-Allow-Origin header to " * " on the back end may clear many CORS errors.
The solution to bypass CORS is to use a Proxy. A Proxy server, that forwards your request as it is. But, problems with a Proxy Server is to manage the server, optimize the server, handle traffic, use of Kubernetes to minimize bills, and what not.
To get rid of a CORS error, you can download a browser extension like CORS Unblock. The extension appends Access-Control-Allow-Origin: * to every HTTP response when it is enabled. It can also add custom Access-Control-Allow-Origin and Access-Control-Allow-Methods headers to the responses.
It looks like the problem was with the axios configurations.
I had this definition: axios.defaults.baseURL = "http://localhost:8080/api";
I changed it to axios.defaults.baseURL = "api";
and it works.
module.exports = {
...
devServer: {
proxy: {
"^/api": {
target: url,
ws: true,
changeOrigin: true
}
}
},
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With