1

我在 CloudAnywhere 中使用 Rails API 设置 CORS 时遇到问题。

我正在尝试在两个单独的 CloudAnywhere 容器中设置一个 React 前端和一个 Rails 后端。(让我们称它们为rails.codeanyapp.comreact.codeanyapp.com。)

React 前端设置了 Rails 的代理(即"proxy": "https://rails.codeanyapp.com"in package.json)。

Rails 后端有以下代码config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'https://react.codeanyapp.com/'

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

GET 请求工作正常。但是,当我进行 POST 时,我在 Rails 中收到以下错误

Started POST "/authors.json" for 104.42.117.130 at 2019-03-19 13:05:52 -0400
Cannot render console from 104.42.117.130! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by AuthorsController#create as JSON
  Parameters: {"fname"=>"James", "lname"=>"madison", "email"=>"james@madison.com", "author"=>{"fname"=>"James", "lname"=>"madison", "email"=>"james@madison.com"}}
HTTP Origin header (https://rails.codeanyapp.com) didn't match request.base_url (https://react.codeanyapp.com)
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)

请注意,已设置 CodeAnywhere,因此https://rails.codeanyapp.com即使服务器实际上在端口 3000 上运行,公共 URL 也是如此。我怀疑当传入端口“转发”到 3000 时问题出在 Rails 端;但是,我认为我没有权限修改这种行为。

另请注意,Origin 和 base 都是 https。(关于这个问题的大多数其他帖子都是当一个是 http 而另一个是 https。)

4

1 回答 1

0

主要问题是我变得懒惰并试图简单地将json渲染放入现有的控制器中。(具体来说,我respond_to在现有控制器中添加了一个块,它是ApplicationController.

正确的解决方案是创建一个单独的控制器,该控制器继承自ApplicationController::API Rails 5 中的 Combining API 和 web 视图

快速而肮脏的解决方案是通过protect_from_forgery unless: -> { request.format.json? }添加application_controller.rb

于 2019-03-20T16:52:11.097 回答