【问题标题】:Nuxtjs Axios in Vuex Module CORS errorVuex 模块 CORS 错误中的 Nuxtjs Axios
【发布时间】:2018-06-25 21:12:36
【问题描述】:

我正在使用 Nuxtjs 和内置的 Vuex 模块以及 Nuxtjs 的官方 axios。我试图从我的本地服务器获取,它总是抛出 CORS 错误。

所以我对 Github 的公共端点进行了 API 调用,但没有成功,只是在我的控制台中收到了 CORS 错误。

我正在使用 Store 操作在组件创建生命周期中启动对服务器的 AJAX 调用。这是我的代码。

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

仍然没有运气。这是一个向控制台抛出的错误消息。

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.

我在这里做错了什么?还是存在于 async/await 中的错误?

更新:奇怪的是网络调用实际上出去并从服务器获取数据,这可以在 Chrome 的网络控制台中看到。

【问题讨论】:

    标签: ajax vue.js promise axios vuex


    【解决方案1】:

    好的,我似乎已经解决了这个问题。

    nuxt.config.js 中,您必须输入credentials: false 以允许使用CORS 通配符。

    我的 axios 配置在这里。

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

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

    【讨论】:

    • 我有类似的问题,但由于 axios.onRequest 中设置的自定义标头值,我想设置 ex.: headers:{ 'X-User-Hash': } 但我是得到这个 -> 跨域资源共享错误:HeaderDissalowedByPreflightResponse 已经将配置设置为@Kaung 之前发布的。有什么想法吗?
    猜你喜欢
    • 2023-03-26
    • 2021-01-27
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2021-10-24
    • 1970-01-01
    相关资源
    最近更新 更多