当我将Rails + React应用部署到Heroku时,我遇到了问题。Rails客户端位于Rails应用程序的client/
目录中。由于使用了react-router
,Rails服务器需要知道如何从React呈现index.html
。当我在Heroku上部署客户机时,脚本会将内容从client/build/.
复制到Rails应用程序的public/
dir。
现在有个问题:当我的路由检测到像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
。这没什么用。
发布于 2018-01-09 08:23:26
我使用的是Rails API,所以我的ApplicationController
继承自ActionController::API
而不是ActionController::Base
。
从Rails API文档中可以看出:
默认的API堆栈包括所有呈现器,这意味着您可以在控制器中自由地使用呈现:json和兄弟。请记住,模板不会被呈现,所以您需要确保控制器在所有操作中都调用render或redirect_to,否则它将返回204No内容。
因此,Rails API只能呈现HTML!以下内容允许我在不包括来自ActionController::Base
的所有内容的情况下呈现html。
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应用程序现在从我的公共目录中呈现index.html,而我的React /react路由器则从那里接管。
https://stackoverflow.com/questions/48140063
复制