How to deal with CORS error on Vue CLI 3?

Access to XMLHttpRequest at ‘http://backend.test/api/data' from origin ‘http://localhost:8080/' has been blocked by CORS policy.
You can watch this article’s video on YouTube.

This error has been my nightmare during the past two months. I tried different solutions available online, from Installing extensions on my browser to altering .htaccess file of the backend project locally, but none of them was ideal. Last night when I was messing around with my Apache configurations I found out that this error could be handled simply by Vue config file provided by Vue CLI 3. If you are struggling with the same problem, you are reading the right article.

To understand the problem and the solution better let's talk a little bit about the error.

Why do we get CORS error?

Browsers protect web applications to interact only with apps that are from the same origin. This is a policy called same-origin. But sometimes it is required to send requests to another server. CORS or Cross-Origin Resource Sharing is a standard that makes cross-origin requests possible by setting specific headers for requests.

In my case, I was serving my Vue application using Vue CLI serve command on localhost:8080 and my backend project was running by apache on a virtual host; Completely against same-origin policy. If somehow it was possible to send Ajax request to the same origin, the problem was solved. There are different ways that we can achieve this behavior by touching server configurations. Since we are frontend developers and server configuration might be different in production, we need some solution that is applied only during development and could be handled in the frontend.

So, how to have the same origin?

Hopefully, Vue CLI provides some properties to achieve this behavior. First, we need to set our Ajax request domain same as our frontend application; In my case: http://localhost:8080/ .

To configure the Vue CLI server, we need to create a vue.config.js file in the root of the frontend project right beside package.json, containing:

// vue.config.js
module.exports = {
// options...
vue.config.js file location inside a Vue project

Inside the module.export you can add configurations for your development server using devServer object. Now we want to configure our development server to proxy API request to the backend domain.

devServer: {
proxy: 'http://backend.test/',

The proxy property is a string of the backend host.

This will tell the dev server to proxy any unknown requests (requests that did not match a static file) to http://backend.test/ __ Vue CLI Configuration

Now you need to serve the app again so that the new configuration applies to the server. And TADA! Your requests don’t need CORS headers anymore.

RECOMMENDATION: I highly recommend using variables inside .env file for storing backend and Ajax base URLs, since the value will be different during production.