Search code examples
ajaxvue.jspromiseaxiosvuex

Nuxtjs Axios in Vuex Module CORS error


I am using Nuxtjs and built-in Vuex modules along with Nuxtjs's official axios. I'm trying to GET from my local server and it always throw CORS error.

So I made an API call to Github's public endpoint, and unsuccessfully only getting CORS error in my console.

I'm using Store actions to launch AJAX calls to server on component create lifecycle. Here is my code.

// component.vue

created () {
   this.$store.dispatch('getGithubAPI')
}

// store action

  async getGithubAPI ({ commit, state }) {
    await this.$axios.$get('https://api.github.com/users/kaungmyatlwin', { headers: { 'Access-Control-Allow-Origin': '*' } })
      .then(resp => {
        console.log(resp.data)
      })
  }

Still no luck of getting it. Here is an error message that was thrown to console.

Failed to load https://api.github.com/users/kaungmyatlwin: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

What did I do wrong here? Or is it an error residing in async/await?

UPDATE: Strange thing is that the network call actually goes out and fetch data from server, as it can be seen in Network console from Chrome.


Solution

  • Ok I seem to have figured out this problem.

    In nuxt.config.js, you have to put credentials: false to allow CORS wildcard.

    My axios config here.

      axios: {
        baseURL: 'https://api.github.com',
        proxyHeaders: false,
        credentials: false
      }
    

    Reference: https://github.com/nuxt-community/axios-module#credentials