【问题标题】:Vue-resource blocked by CORS policyVue 资源被 CORS 策略阻止
【发布时间】:2019-08-05 17:43:01
【问题描述】:

我知道有一些类似的胎面,但没有一种解决方案可以帮助我。

我正在使用 Ruby on Rails 和 Vue 构建一个应用程序。目前,我正在尝试获取我的用户的 Spotify 访问令牌。所以我只需要创建一个获取请求并等待响应。

它在使用 Rails 创建的视图中完美运行,但不是在我的 Vue 应用程序中。

这是我控制台中的错误:

Access to XMLHttpRequest at 'https://accounts.spotify.com/authorize?client_id=261c008xxxxxx52da843b8096d&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fspotify%2Fcallback&response_type=code&scope=playlist-modify-public+user-read-email&state=5987fec3952e0c46332183c526d0abef2f0d35a13e39694e' (redirected from 'http://localhost:3000/auth/spotify') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

请求的资源上不存在“Access-Control-Allow-Origin”标头。但如果我们检查标头:

在我的 js 文件中,我有:

Vue.http.interceptors.push(function (request, next) {
  request.headers.set('Content-Type', 'application/json');
  request.headers.set('Access-Control-Allow-Origin', '*');
  request.headers.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  request.headers.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  request.headers.set('X-CSRF-Token', document.getElementsByName('csrf-token')[0].content);
  next();
});

我不知道去哪里找,你有什么想法吗? 我已经尝试安装 chrome 扩展,允许所有来源在我的服务器端,用 Axios 替换 Vue-resource,用 node 安装 cors...

【问题讨论】:

  • 你为什么要打 XHR 电话?

标签: ruby-on-rails vue.js vue-resource


【解决方案1】:

Access-Control-Allow-Origin 应该是 response 标头而不是请求标头。您的后端 API 必须设置它。

【讨论】:

  • 嗨@Flame,感谢您的回答。我正在使用 Spotify 的 API,它适用于 Ruby,但不适用于 Vue,这就是为什么我不明白问题出在哪里
  • 浏览器使用allow-origin标头来告诉哪些来源可以访问资源(即哪些域)。当您从 Ruby 发出请求时,这是在服务器端完成的,并且它不是来自域,因此它可以工作。在 Javascript 中,标头由浏览器检查,并且可以阻止请求
猜你喜欢
  • 2021-10-13
  • 1970-01-01
  • 2020-08-27
  • 2020-08-29
  • 2020-09-11
  • 2021-04-16
  • 2018-02-26
  • 2019-11-19
  • 2020-09-12
相关资源
最近更新 更多