带有主页的 Rails 5 api 唯一应用程序 [英] Rails 5 api only app with home page

查看:16
本文介绍了带有主页的 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 获取/home/index"由 HomeController#index 处理为 HTML Completed 204 No Content in0ms

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 开始 GET "/home/index.js" for 127.0.0.1+0530 HomeController#index 作为 JS 完成的处理 204 在 0 毫秒内没有内容

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 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.

这篇关于带有主页的 Rails 5 api 唯一应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆