且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有主页的 Rails 5 api 唯一应用程序

更新时间:2023-11-22 17:23:04

我在同一条船上,试图做一个 Rails 5 API 应用程序,它仍然可以从单个 html 页面引导(在加载时由 JS 接管).从 rails source 中窃取提示,我创建了以下控制器(注意它使用 Rails 代替我的 ApplicationController 作为这个单独的非 api 控制器)

I was in the same boat, trying to do a Rails 5 API app that could still bootstrap from a single html page (taken over by JS on load). Stealing a hint from rails source, I created the following controller (note that it's using Rails' instead of my ApplicationController for this lone non-api controller)

require 'rails/application_controller'

class StaticController < Rails::ApplicationController
  def index
    render file: Rails.root.join('public', 'index.html')
  end
end

并将相应的静态文件(纯.html,而不是.html.erb)放在public 文件夹中.我也加了

and put the corresponding static file (plain .html, not .html.erb) in the public folder. I also added

get '*other', to: 'static#index'

routes.rb 的末尾(在我所有的 api 路由之后),以便为重新加载、深层链接等保留客户端路由.

at the end of routes.rb (after all my api routes) to enable preservation of client-side routing for reloads, deep links, etc.

无需在 routes.rb 中设置 root,Rails 将在调用 / 时直接从 public 提供服务,否则将在非 API 路由上命中静态控制器.根据您的用例,添加 public/index.html(在 routes.rb 中没有 root)可能就足够了,或者您可以在没有奇怪的情况下实现类似的事情 StaticController 使用

Without setting root in routes.rb, Rails will serve directly from public on calls to / and will hit the static controller on non-api routes otherwise. Depending on your use-case, adding public/index.html (without root in routes.rb) might be enough, or you can achieve a similar thing without the odd StaticController by using

get '*other', to: redirect('/')

相反,如果您不关心路径保留.

instead, if you don't care about path preservation.

我很想知道是否有人有更好的建议.

I'd love to know if anyone else has better suggestions though.