How to resolve CORS issue in VueJs
Tags: webdev, beginners, vue, javascript
Published: 2022-06-26 16:24:22

Web applications often depend on resources from an external source or domain. For example, a website can display an image hosted on another site. Beyond images, a web application may fetch JSON format data from an external API. 

However, sharing resources across websites isn't always a smooth ride. If you've made HTTP requests from JavaScript to another site, you've probably seen a **CORS** error. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nrqt8906v5z9v3gdri69.png)
   In this blog I'm going to explain what is CORS policy & how to resolve the CORS problem.  

Let's get started...

## What Is CORS?


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69llltd1s4gejoavmmqd.png)

The full meaning of CORS is Cross-Origin Resource Sharing. CORS is a mechanism that can be found in modern web browsers like Chrome, Firefox, Safari, and Edge. It prevents **Domain A** from accessing resources on **Domain B** without explicit permission. 

For reproducing this issue, I have developed a simple **golang** based backend project & I integrated the APIs with VueJs frontend code.

Vue will spin up a simple web server that listens on port 8080 and serves the frontend. This is great for easy development, but we will run into problems when calling our API.

Let’s open the http://localhost:8080 page:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mvxpq3xgbcwvz0ojz9ge.png)
We can see that while triggering the API call browser gives a CORS error. This is because http://localhost:8080 and http://localhost:3000 are considered different domains and thus the CORS policy comes into play.

## How To Fix CORS Errors

We can fix this CORS problem in two ways, 

#### 1) Allow CORS requests from the backend server

With the **Access-Control-Allow-Origin** header, we can specify what origins can use our API.

We can set it to http://localhost:8080 or '*' to allow our Vue app to call it:

```go
func respondWithJson(w http.ResponseWriter, code int, payload interface{}) {
	response, _ := json.Marshal(payload)
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.WriteHeader(code)
	w.Write(response)
}
```

#### 2) Setup a development proxy in VueJs

During development, you often see that the backend server is running on a different port than the frontend server.

This is also the case with our example where the frontend server runs on localhost:8080 and the backend server runs on localhost:3000.

To set up this proxy system, we can create a **vue.config.js** file in the root of the Vue project:

```js
module.exports = {
  devServer: {
    proxy: {
      '^/users': {
        target: 'http://localhost:3000/',
        ws: true,
        changeOrigin: true
      },
    }
  }
}
```
We should then also change the backend urls in the Axios calls. That is, instead of providing the backend URL either we need to remove the domain or we should provide the FrontEnd domain. 

```js
listUsers(){
   var url = "/users";
   return axios({
      url: url,
      method: 'GET',
   }).then(result => {
      this.model = result.data;
      this.$emit('listUsers', this.model);
      return result;
   }).catch(error => {
      console.log(error);
      throw error;
   });
},
```
Here, I removed the domain while making the API call.

Let’s try it again!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/49sb467psy49f5z9elkc.png)

Now we see that the browser is allowed to access the API.