How to fix the CORS issue in Vuejs
Imagine the first day in which you want to connect and implement API(s) from the back-end into your front-end project. Suddenly when you call those API(s) something going wrong, and you likely see this error in your console.
Access to XMLHttpRequest at ‘http://api.back.end/data' from origin ‘http://localhost:8080/' has been blocked by CORS policy.
Boom, everything breaks down. This is a nightmare for developers. But how we can deal with this? Before solving the problem we should deep dive into this error.
Why do we get CORS error? What really is CORS?
This is a common policy on the web we call it same-origin, which means web applications should interact with other services from the same origin. But sometimes it is required to send a request to another service — server, back-end, API, and etc. CORS makes it possible to set a specific header on the request to the server. you can read widely about Cross-Origin Resource Sharing (CORS).
In my case, I was serving my Vuejs project on localhost
and the API service was running on the server. As you can guess they're were from different origins completely against the same-origin policy as I mentioned. We assume you haven't any access to change the Back-end configuration.
so, How we can deal with CORS error?
Yes, we should have same-origin, But how? Hopefully we can achieve this easily with Vue CLI. In my case, the Front-end project was running on localhost:8080
. We actually need to proxy the API requests to the Back-end during development.
To config this setting, you should put the proxy URL into this file vue.config.js
if you haven't this file yet in your project, first, you need to create the file right beside the package.json in the root of the project.
// vue.config.js
module.exports = {
// options...
}
Inside module.exports
you can put your configuration using devServer
the object. Because we want to config our development server to proxy API requests to the Back-end Endpoint.
// vue.config.js
module.exports = {
devServer: {
proxy: 'http://api.back.end',
}
}
This will tell the dev server to proxy any unknown requests (requests that did not match a static file) to http://api.back.end.
Now you need to terminate your app and run it again so that new configurations will be applied to the server. Just that, easy peasy lemon squeezy :))
You can find other configurations here Vue configurations.
If you want to get rid of this issue temporarily just install this chrome extension CORS Unblock.