问题
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
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
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.
Kindly share your thoughts.
回答1:
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
and put the corresponding static file (plain .html
, not .html.erb
) in the public
folder. I also added
get '*other', to: 'static#index'
at the end of routes.rb
(after all my api routes) to enable preservation of client-side routing for reloads, deep links, etc.
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.
回答2:
If all you need is just a static HTML page (with some simple css/js), i think another method is just to edit the index.html
page under public
folder.
来源:https://stackoverflow.com/questions/38366501/rails-5-api-only-app-with-home-page