我有一个Rails API应用程序和一个单独的React应用程序。
我想创建一个控制器,将整个应用程序返回给最终用户,让react应用程序从专用控制器使用API,而不是创建两个服务器。
我怎么能这样做呢?
react应用程序树是:
在这个问题上不是很有经验,但如果它会有所帮助,这就是我在最近的项目中所做的:
# 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'
def bootstrapper
render template: 'layouts/bootstrapper'
end
<!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>
import
了解详情Rails.csrfToken()
头传递。确保你的app / assets / javascripts / application.js中有'X-CSRF-Token'
,你可以使用//= require rails-ujs
我不能直接写你如何连接它们,它会有点冗长,但这里有一个链接,可以让你在路上:
Rails.csrfToken()
通常,您所做的只是创建'Rails API'应用程序并使用您的控制器呈现json并使用React fetch / axios连接到您的Rails API