在 Nuxt.js 中 CORS 阻塞客户端请求

Man*_*anu 7 cors vuex vuejs2 nuxt.js

我在提出客户请求时遇到问题。

我遵循了Nuxt.jsAxios上的文档,但我似乎仍然无法让它工作。也许我错过了一些东西..

我的 Vue 组件调用vuex 操作

methods: {
  open() {
    this.$store.dispatch('events/getEventAlbum');
  }
}
Run Code Online (Sandbox Code Playgroud)

行动vuex

export const actions = {
  async getEventAlbum(store) {
    console.log('album action');
    const response = await Axios.get(url + '/photos?&sign=' +   isSigned + '&photo-host=' + photoHost);
    store.commit('storeEventAlbum', response.data.results);
  }
};
Run Code Online (Sandbox Code Playgroud)

还有我的nuxt.js.config

modules: [
  '@nuxtjs/axios',
  '@nuxtjs/proxy'
],

axios: {
  proxy: true
},

proxy: {
  '/api/': { target: 'https://api.example.com/', pathRewrite: {'^/api/': ''} }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供帮助?

Dan*_*iel 19

我相信@andrew1325 试图指出的问题是API 提供者需要启用 CORS,而不仅仅是您的服务器,在不更改代理中的标头的情况下,您正在传递相同的标头,目前阻止使用权。

在我看来你只是失踪 changeOrigin

请尝试以下配置:

modules: [
  '@nuxtjs/axios',
  '@nuxtjs/proxy'
],

axios: {
  proxy: true
},

proxy: {
  '/api/': { target: 'https://api.example.com/', pathRewrite: {'^/api/': ''}, changeOrigin: true }
}
Run Code Online (Sandbox Code Playgroud)

还要确保您的前端 API url 指向您的代理请求 /api

  • 如果您将其作为链接粘贴,则这是浏览器的安全策略,CORS 不是问题。你需要使用 `https://api.example.com/2/` 作为你的 **proxy target** 并在你的应用程序中使用 `/api` **。这就是代理的用途,它通过服务器而不是浏览器来路由流量。 (9认同)