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


This content originally appeared on DEV Community and was authored by Gayathri R

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

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

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;
   });
},

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.


This content originally appeared on DEV Community and was authored by Gayathri R


Print Share Comment Cite Upload Translate Updates
APA

Gayathri R | Sciencx (2022-06-26T16:24:22+00:00) How to resolve CORS issue in VueJs. Retrieved from https://www.scien.cx/2022/06/26/how-to-resolve-cors-issue-in-vuejs/

MLA
" » How to resolve CORS issue in VueJs." Gayathri R | Sciencx - Sunday June 26, 2022, https://www.scien.cx/2022/06/26/how-to-resolve-cors-issue-in-vuejs/
HARVARD
Gayathri R | Sciencx Sunday June 26, 2022 » How to resolve CORS issue in VueJs., viewed ,<https://www.scien.cx/2022/06/26/how-to-resolve-cors-issue-in-vuejs/>
VANCOUVER
Gayathri R | Sciencx - » How to resolve CORS issue in VueJs. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/06/26/how-to-resolve-cors-issue-in-vuejs/
CHICAGO
" » How to resolve CORS issue in VueJs." Gayathri R | Sciencx - Accessed . https://www.scien.cx/2022/06/26/how-to-resolve-cors-issue-in-vuejs/
IEEE
" » How to resolve CORS issue in VueJs." Gayathri R | Sciencx [Online]. Available: https://www.scien.cx/2022/06/26/how-to-resolve-cors-issue-in-vuejs/. [Accessed: ]
rf:citation
» How to resolve CORS issue in VueJs | Gayathri R | Sciencx | https://www.scien.cx/2022/06/26/how-to-resolve-cors-issue-in-vuejs/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.