当我将我的 Rails + React 应用程序部署到 Heroku 时,我遇到了问题。 React 客户端位于 Rails 应用程序的 client/
目录中。由于使用了 react-router
,Rails 服务器需要知道从 React 构建中渲染 index.html
。当我在 Heroku 上部署客户端时,脚本将内容从 client/build/.
复制到 Rails 应用程序的 public/
目录。
现在问题来了:当我的路由检测到类似 example.com/about 的路径时,它会尝试呈现 public/index.html
。方法如下:
def fallback_index_html
render file: "public/index.html"
end
但是,此文件的内容不会发送到浏览器。我得到一个空白页。我在方法中添加了一个 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>
我最近尝试的修复是进入 config/environments/production.rb
并将 config.public_file_server.enabled
更改为 true
。这没有帮助。
最佳答案
我正在使用 Rails API,所以我的 ApplicationController
继承自 ActionController::API
而不是 ActionController::Base
。
从 Rails API 文档中说:
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.
因此只有 Rails API 无法呈现 HTML!以下允许我渲染 html,而不包括 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
我包含 ActionController::MimeResponds
的原因是可以访问 respond_to
方法。
我的 Rails 应用程序现在在点击子目录时从我的公共(public)目录呈现 index.html,并且我的 React 客户端/react-router 从那里接管。
关于ruby-on-rails - Rails 不呈现 public/index.html 文件;浏览器中的空白页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48140063/