Vuex 模块 CORS 中的 Nuxtjs Axios 错误 [英] Nuxtjs Axios in Vuex Module CORS error

查看:23
本文介绍了Vuex 模块 CORS 中的 Nuxtjs Axios 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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.

<代码>无法加载 https://api.github.com/users/kaungmyatlwin:对预检请求的响应未通过访问控制检查:响应中Access-Control-Allow-Origin"标头的值不得为当请求的凭据模式为包含"时,通配符*".因此,不允许访问 Origin 'http://localhost:3000'.XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制.

我在这里做错了什么?或者是 async/await 中的错误?

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

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

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.

推荐答案

好吧,我似乎已经解决了这个问题.

Ok I seem to have figured out this problem.

nuxt.config.js 中,你必须把 credentials: false 放在允许 CORS 通配符.

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

我的 axios 配置在这里.

My axios config here.

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

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

这篇关于Vuex 模块 CORS 中的 Nuxtjs Axios 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆