如何在Rails 5 API中呈现文件?

我有一个用React编写的单页面应用程序和Ruby on Rails后端(API模式)。 Rails也提供静态文件。 我将Rails路由器指向public/index.html ,因此我的SPA可以使用react-router管理自己的路由。 这是通常的做法,以便使直接链接和刷新工作。

的routes.rb

 match '*all', to: 'application#index', via: [:get] 

application_controller.rb

 class ApplicationController < ActionController::API def index render file: 'public/index.html' end end 

问题是这在API模式下不起作用。 这只是一个空洞的回应。 如果我将父类更改为ActionController::Base一切都按预期工作。 但我不想inheritance全class的膨胀,我需要纤薄的API版本。

我尝试添加ActionController::Renderers::AllAbstractController::Rendering但没有成功。

如果我将父类更改为ActionController :: Base,则一切都按预期工作。 但我不想inheritance全class的膨胀,我需要纤薄的API版本。

是的,如果从ApplicationController提供索引,更改其基类将影响所有其他控制器。 这个不好。 但是如果你有一个专门的控制器来服务这个页面呢?

 class StaticPagesController < ActionController::Base def index render file: 'public/index.html' end end 

这样,你只有一个“臃肿”的控制器,而其他人仍然保持苗条和快速。

这应该工作,并允许您继续从ActionController :: API–

 class ApplicationController < ActionController::API def index respond_to do |format| format.html { render body: Rails.root.join('public/index.html').read } end end end 

使用Rails 5为ActionController :: API更改了渲染逻辑。

你可以做到

 render text: File.read(Rails.root.join('public', 'index.html')), layout: false