Rails不呈现public / index.html文件;浏览器中的空白页

ste*_*ade 7 ruby ruby-on-rails heroku reactjs react-router

将我的Rails + React应用程序部署到Heroku时遇到问题。React客户端位于client/Rails应用程序的目录中。由于使用react-router,Rails服务器需要知道index.html从React构建中渲染。当我在Heroku上部署客户端时,脚本会将内容从复制client/build/.到Rails应用程序的public/目录。

现在是问题所在:当我的路线检测到诸如example.com/about之类的路径时,它将尝试渲染public/index.html。方法如下:

def fallback_index_html
   render file: "public/index.html"
end
Run Code Online (Sandbox Code Playgroud)

但是,该文件中的内容不会发送到浏览器。我得到空白页。我puts "hit fallback_index_html"在方法中添加了一个,并确认该方法已被执行。我还打开了puts文件,以确认文件具有所需的html(这是该puts日志中显示的内容,以及应发送给浏览器的内容):

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="/manifest.json">
    <link rel="shortcut icon" href="/favicon.ico">
    <title>Simple Bubble</title>
    <link href="/static/css/main.65027555.css" rel="stylesheet">
</head>

<body><noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script type="text/javascript" src="/static/js/main.21a8553c.js"></script>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

我尝试过的最新修复方法是config/environments/production.rb并更改config.public_file_server.enabled为true。这没有帮助。

ste*_*ade 6

I'm using Rails API, so my ApplicationController inherits from ActionController::API instead of ActionController::Base.

From Rails API docs it says:

The default API Controller stack includes all renderers, which means you can use render :json and brothers freely in your controllers. Keep in mind that templates are not going to be rendered, so you need to ensure your controller is calling either render or redirect_to in all actions, otherwise it will return 204 No Content.

Thus Rails API only cannot render HTML! The following allowed me to render the html without including everything from ActionController::Base.

class ApplicationController < ActionController::API
  include ActionController::MimeResponds

  def fallback_index_html
    respond_to do |format|
      format.html { render body: Rails.root.join('public/index.html').read }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

The reason I am including ActionController::MimeResponds is to have access to the respond_to method.

My Rails application now renders index.html from my public directory when a subdirectory is hit and my React client / react-router takes over from there.