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

问题描述 投票:0回答:2

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

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

我怎么能这样做呢?

react应用程序树是:

  • 上市 favicon.ico的 的index.html 的manifest.json
  • SRC 资产/ 其它的组件/ 查看/ App.css App.js index.css index.js registerServiceWorkder.js
  • 自述
  • 的package.json
  • 包lock.json
javascript ruby-on-rails ruby reactjs integration
2个回答
2
投票

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

  • 使用/将webpacker gem集成到您的Rails项目中
  • 应用程序/配置/ 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'
  • 应用程序/控制器/ application_controller.rb: def bootstrapper render template: 'layouts/bootstrapper' end
  • 应用程序/视图/布局/ 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文件的入口点,所以你可以在这里找到你的React应用程序)请参阅import了解详情

奖金

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

0
投票

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

  1. 这个链接讨论了'create-react-app',这是你创建反应应用程序和Rails API所做的。

Rails.csrfToken()

通常,您所做的只是创建'Rails API'应用程序并使用您的控制器呈现json并使用React fetch / axios连接到您的Rails API

© www.soinside.com 2019 - 2024. All rights reserved.