首页 文章

Rails控制器返回一个完整的反应应用程序

提问于
浏览
0

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

我想创建一个控制器,将整个应用程序返回给最终用户,让react应用程序从专用控制器使用API,而不是创建两个服务器 .

我怎么能整齐地做到这一点?

react应用程序树是:

  • 公众

  • favicon.ico

  • index.html

  • manifest.json

  • src

  • 资产/

  • Componenets /

  • 意见/

  • App.css

  • App.js

  • index.css

  • index.js

  • registerServiceWorkder.js

  • 自述文件

  • package.josn

  • package-lock.json

2 回答

  • 2

    在这个问题上不是很有经验,但如果它会有所帮助,这就是我在最近的项目中所做的:

    • 在您的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()
  • 0

    我不能直接写你如何连接它们,它会有点冗长,但这里有一个链接,可以让你在路上:

    • 此链接讨论'create-react-app',这是您创建反应应用程序和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

相关问题