【问题标题】:Rails controller to return a whole react appRails 控制器返回整个反应应用程序
【发布时间】:2018-06-02 10:11:18
【问题描述】:

我有一个 Rails API 应用程序和一个单独的独立 React 应用程序。

我想创建一个控制器,将整个应用程序返回给最终用户,并让反应应用程序使用来自专用控制器的 API,而不是创建两个服务器。

我怎样才能巧妙地做到这一点?

react 应用树是:

  • 公开
    • favicon.ico
    • index.html
    • manifest.json
    • 资产/
    • 组件/
    • 观看次数/
    • App.css
    • App.js
    • index.css
    • index.js
    • registerServiceWorkder.js
  • 自述文件
  • package.josn
  • package-lock.json

【问题讨论】:

  • 您可能希望将 JS 捆绑到资产管道中。有关于如何做到这一点的教程。
  • 在您的路线中进行设置。根路径应交付客户端应用程序。其余的可以是 API。

标签: javascript ruby-on-rails ruby reactjs integration


【解决方案1】:

在这件事上不是很有经验,但如果有帮助,这就是我在最近的项目中所做的:

  • 在您的 Rails 项目中使用/集成webpacker gem

  • app/config/routes.rb

    # all JSON requests goes here
    scope constraints: -> (request) { request.format == :json } do
      # all of your Rails API routes goes here
    end
    
    # all HTML requests goes here,
    # as your react-router should already be able to handle this
    scope constraints: -> (request) { request.format == :html } do
      # this matches ALL paths to bootstrapper action
      match '*path', to: 'application#bootstrapper'
    end
    
    root 'application#boostrapper'
    
  • app/controllers/application_controller.rb

    def bootstrapper
      render template: 'layouts/bootstrapper'
    end
    
  • app/views/layouts/bootstrapper.html.erb

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <!-- YOUR USUAL <head> HERE -->
        <%= stylesheet_link_tag    "application" %>
        <%= javascript_include_tag "application" %>
        <%= csrf_meta_tags %>
      </head>
      <body>
        <!-- DONT NEED THE <%= yield %> HERE -->
        <%= javascript_pack_tag 'your_react_pack' %>
        <%= stylesheet_pack_tag 'your_react_pack' %>
      </body>
    </html>
    
  • 最后配置您的 app/javascript/packs/your_react_pack.js(这是您的 React 文件的入口点,因此您将在此处 import 您的 React 应用程序)详情见webpacker

奖金

  • 跨站请求伪造 (CSRF) 保护是必须的!在 Rails 5(或者也可能是 4?)中,您可以简单地使用 Rails.csrfToken() 在 JS 中获取令牌,并在向 Rails 应用程序提交 JSON 请求时将其作为 'X-CSRF-Token' 标头传递。确保您的 app/assets/javascripts/application.js 中有 //= require rails-ujs 以便您能够使用 Rails.csrfToken()

【讨论】:

    【解决方案2】:

    我不能直接写出如何连接它们,这会有点冗长,但这里有一个链接可以帮助你:

    1. 此链接讨论的是“create-react-app”,这是您创建 React 应用程序和 Rails API 时所做的。

    https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/

    一般来说,您所做的只是创建“Rails API”应用程序并使用控制器渲染 json,然后使用 React fetch/axios 连接到您的 Rails API

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多