繁体   English   中英

如何在 codeanywhere 中配置 React API 代理

[英]How to configure React API proxy in codeanywhere

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

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

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

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 已设置,因此公共 URL 为https://rails.codeanyapp.com即使服务器实际上在端口 3000 上运行。当传入端口“转发”到 3000 时,我怀疑问题出在 Rails 端; 但是,我认为我无权修改这种行为。

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

主要问题是我很懒惰并试图简单地将json渲染扔到现有控制器中。 (具体来说,我向作为ApplicationController子类的现有控制器添加了一个respond_to块。) 这样做的问题是,默认情况下,Rails 添加 CSRF 和其他不能完全应用于 API 的中间件。

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

快速而肮脏的解决方案是通过添加protect_from_forgery unless: -> { request.format.json? }来关闭API 调用的CSRF, protect_from_forgery unless: -> { request.format.json? } protect_from_forgery unless: -> { request.format.json? }application_controller.rb

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM