DEV Community

Cover image for How to resolve CORS issue in VueJs
Gayathri R
Gayathri R

Posted on • Updated on

How to resolve CORS issue in VueJs

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
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

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
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:

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)
}
Enter fullscreen mode Exit fullscreen mode

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:

module.exports = {
  devServer: {
    proxy: {
      '^/users': {
        target: 'http://localhost:3000/',
        ws: true,
        changeOrigin: true
      },
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

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;
   });
},
Enter fullscreen mode Exit fullscreen mode

Here, I removed the domain while making the API call.

Let’s try it again!

Image description

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

Top comments (1)

Collapse
 
fyodorio profile image
Fyodor

It’s important to mention that both ways are not suitable for production purposes. Though they can definitely be useful for dev purposes and for understanding the client-server communication mechanics and security implications of it.