【问题标题】:CORS blocking client request in Nuxt.js在 Nuxt.js 中 CORS 阻止客户端请求
【发布时间】:2019-08-22 00:48:27
【问题描述】:

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

我已按照 Nuxt.jsAxios 上的文档进行操作,但似乎仍然无法正常工作。也许我错过了什么..

我的 Vue 组件调用 vuex 操作

methods: {
  open() {
    this.$store.dispatch('events/getEventAlbum');
  }
}

vuex中的action

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

还有我的 nuxt.js.config

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

axios: {
  proxy: true
},

proxy: {
  '/api/': {
    target: 'https://api.example.com/',
    pathRewrite: { '^/api/': '' }
  }
}

谁能帮忙?

【问题讨论】:

  • 这将是您的 api 阻止请求。您在控制台中遇到的 cors 错误是什么?你用的是什么类型的api?
  • 嗨@Andrew1325,这是一个 RESTful API,我收到 No 'Access-Control-Allow-Origin' 标头 错误。跨度>
  • 你的 api 是 express (node.js) api吗?
  • @Andrew1325 ,是的,Nuxt.js 是建立在 Node & Express 之上的
  • @Manu 不,Nuxt 构建在 Vue.js 之上,显然是 Node.js。 Express 只是一个集成。

标签: vuejs2 cors vuex nuxt.js


【解决方案1】:

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

在我看来你只是缺少changeOrigin

请尝试以下配置:

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

axios: {
  proxy: true
},

proxy: {
  '/api/': { target: 'https://api.example.com/', pathRewrite: {'^/api/': ''}, changeOrigin: true }
}

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

【讨论】:

  • 您好 Daniel,changeOrigin 并没有太大的不同。仍然遇到同样的错误.. Access to XMLHttpRequest at 'https://api.example.com/2/photos?&sign=true&photo-host=public&event_id=testID' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • 那么您根本没有访问代理,因此您通过配置设置了什么并不重要,因为您完全绕过了它。你能显示url (const response = await Axios.get(url + ...) 的代码吗?你可能只需要这样做/api
  • 如果我将链接 https://api.example.com/2/photos?&sign=true&photo-host=public&event_id=testID 粘贴到我的浏览器中,它可以正常工作,所以我很确定我的 Axios.get() 中的任何内容都没有问题
  • 如果您将其粘贴为链接,这是浏览器的安全策略,CORS 不是问题。您需要使用https://api.example.com/2/ 作为您的代理目标,并在您的应用程序中使用/api。这就是代理的作用,它通过服务器而不是浏览器获取流量。
  • 这可以在 Netlify 静态站点上运行吗?
猜你喜欢
  • 1970-01-01
  • 2020-03-26
  • 2021-02-04
  • 2018-10-18
  • 2020-08-16
  • 2022-11-01
  • 2015-09-10
  • 1970-01-01
  • 2020-02-20
相关资源
最近更新 更多