简体   繁体   English

Vuex 模块 CORS 中的 Nuxtjs Axios 错误

[英]Nuxtjs Axios in Vuex Module CORS error

I am using Nuxtjs and built-in Vuex modules along with Nuxtjs's official axios.我正在使用 Nuxtjs 和内置的 Vuex 模块以及 Nuxtjs 的官方 axios。 I'm trying to GET from my local server and it always throw CORS error.我试图从我的本地服务器获取,但它总是抛出 CORS 错误。

So I made an API call to Github's public endpoint, and unsuccessfully only getting CORS error in my console.因此,我对 Github 的公共端点进行了 API 调用,但没有成功,仅在我的控制台中收到 CORS 错误。

I'm using Store actions to launch AJAX calls to server on component create lifecycle.我正在使用 Store 操作在组件创建生命周期中启动对服务器的 AJAX 调用。 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?或者它是驻留在 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.更新:奇怪的是,网络调用实际上出去并从服务器获取数据,正如在 Chrome 的网络控制台中可以看到的那样。

Ok I seem to have figured out this problem.好吧,我似乎已经找到了这个问题。

In nuxt.config.js , you have to put credentials: false to allow CORS wildcard.nuxt.config.js ,您必须放置credentials: false以允许 CORS 通配符。

My axios config here.我的 axios 配置在这里。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM