【问题标题】:I set up CORS in my Rails app, but I still get the error [duplicate]我在我的 Rails 应用程序中设置了 CORS,但我仍然收到错误 [重复]
【发布时间】:2019-08-11 05:44:25
【问题描述】:

我在 gemfile gem 'rack-cors', require: 'rack/cors' 中有它。我做了捆绑安装。

我也在config/initializers/cors.rb中设置了

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
   end
 end

之后我确实重启了服务器。

这是我得到的错误:

Access to XMLHttpRequest at 'localhost:3000/articles' from origin 'http://localhost:8080' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

这是我的回购Portfolio_App

【问题讨论】:

  • curl -I -X OPTIONS -H "Access-Control-Request-Method: POST" -H "Origin: example.org" localhost:3000/articles 的输出是什么?
  • HTTP/1.1 200 OK Content-Type: text/plain Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD Access-Control-Expose-Headers: Access-Control-Max-Age: 1728000 Transfer-Encoding: chunked
  • 另外请发布发出 XMLHttpRequest 的 js
  • 这已被标记为重复问题,但我不知道是不是。 [CORS 错误:“请求仅支持协议方案:http…”] 没有解释我可能在 Rails 应用程序上遇到问题的地方。我的问题是关于在 Rails 上设置 CORS。它可能与最后的另一个问题有相同的答案,但它不是同一个问题。我不会知道这个问题回答了我的问题。

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


【解决方案1】:

在您的vue_portfolio/src/components/Articles.vue 中有axios.get('localhost:3000/articles'),没有协议它不是绝对的不是相对的,浏览器认为您正在尝试通过协议localhost 连接到主机3000 并且不允许。

改成

axios.get('http://localhost:3000/articles') 

axios.get('/articles') 

(后者是同源的,这种情况下不需要CORS)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2017-11-16
    • 2021-03-28
    • 2018-04-29
    • 2014-08-06
    • 2019-07-18
    • 2017-07-06
    相关资源
    最近更新 更多