CORS issue with Vue.js

desicne picture desicne · Nov 29, 2016 · Viewed 101.5k times · Source

I'm using:

  • Vue 2.0.3
  • vue-router 2.0.1
  • vuex 0.8.2
  • vue-resource 0.7.0

And after trying to login to my page when using remote API, not the locally run one, I get cors error like following

vue-resource.common.js?2f13:1074 OPTIONS 

https://mywebsite/api/auth/login 

(anonymous function) @     vue-resource.common.js?2f13:1074
Promise$1            @     vue-resource.common.js?2f13:681
xhrClient            @     vue-resource.common.js?2f13:1033
Client               @     vue-resource.common.js?2f13:1080
(anonymous function) @     vue-resource.common.js?2f13:1008


XMLHttpRequest cannot load https://mywebsite/api/auth/login. 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://localhost:8080' is therefore not allowed 
access. The response had HTTP status code 415.

Now I have API running in Azure, and since it allows me to test my calls from Postman, I am quite sure the CORS headers are set properly on backend. Not so sure about the Vue and the front.

I have situation like this in config files:

export const API_ROOT = 'https://mywebsite/api/'
export const AuthResource = Vue.resource(API_ROOT + 'auth{/action}')

than i.e I am calling this action like:

login: function (userData) {
    return AuthResource.save({action: 'login'}, userData)
}

Finally as I am checking auth in login via token in vuex submodule I have just a simple header check-up state.

var updateAuthHeaders = () => {
    var token = JSON.parse(localStorage.getItem("auth_token"))
    if (token != null){
        Vue.http.headers.common['Authorization'] = token
    }else{
        Vue.http.headers.common['Authorization'] = null
    }
}

I have tried adding Vue.http.headers.common['Access-Control-Allow-Origin'] = true here, but did not help the case.

Any idea? What am I doing wrong.. I suppose it will not work for other calls also if it doesn't work for login.

Answer

Negar picture Negar · Apr 7, 2019

You face this error when the API url and client url aren't the same. Vue CLI 3 (and in the core of it, Webpack) allows you to proxy your API url to your client url.

Inside vue.config.js file add following lines:

// vue.config.js
module.exports = {
  // options...
  devServer: {
        proxy: 'https://mywebsite/',
    }
}

And then send your ajax calls to http://localhost/api/.

You can read the full article here: How to deal with CORS error on Vue CLI 3?