带有主页的仅Rails 5 API应用程序

问题描述:

我已经生成了Rails 5 API应用程序.但是我想要我的应用带有主页.为此,我生成了一个家庭控制器,并在各自的views/home/index.html.erb

I have generated a rails 5 api application. But I want my app with home page. For that I generated a home controller and added view file i respective views/home/index.html.erb

但是当我尝试访问它时,我得到的响应低于要求

But when I tried accessing it I am getting below response

在2016-07-14 11:14:03 +0530开始为127.0.0.1获取GET"/home/index" 由HomeController#index处理为HTML已完成204中没有内容 0毫秒

Started GET "/home/index" for 127.0.0.1 at 2016-07-14 11:14:03 +0530 Processing by HomeController#index as HTML Completed 204 No Content in 0ms

在2016-07-14 11:14:20为127.0.0.1启动GET"/home/index.js" +0530由HomeController#index处理为JS已完成204在0ms内没有内容

Started GET "/home/index.js" for 127.0.0.1 at 2016-07-14 11:14:20 +0530 Processing by HomeController#index as JS Completed 204 No Content in 0ms

但是我看不到网络上显示的索引页面内容.

But I could not see index page content displayed on the web.

请分享您的想法.

我在同一条船上,试图做一个Rails 5 API应用程序,该应用程序仍然可以从单个html页面进行引导(在加载时由JS接管).窃听 rails源的提示,我创建了以下控制器(注意它将它用于单独的非API控制器而不是我的ApplicationController)

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将在调用/时直接从公共服务,否则将在非API路由*问静态控制器.根据您的用例,添加public/index.html(在routes.rb中没有根)可能就足够了,或者您可以通过使用

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.