使用Sinatra提供静态文件服务

143

我有一个只使用HTML、CSS和JavaScript的单页面网站。 我想将应用程序部署到Heroku,但是我找不到方法来实现。 现在我正在尝试使用Sinatra让应用程序工作。

.
|-- application.css
|-- application.js
|-- index.html
|-- jquery.js
`-- myapp.rb

以下是myapp.rb的内容。

require 'rubygems'
require 'sinatra'

get "/" do
  # What should I write here to point to the `index.html`
end

1
我已经学会了访问 http://localhost:2345/index.html 的方法。 - TK.
你可以使用 WebBrick 在几行代码中提供静态文件服务。require 'webrick'; server = WEBrick::HTTPServer.new Port: 1234; server.mount '/', WEBrick::HTTPServlet::FileHandler, 'www/'; trap("INT") { server.stop }; server.start; 然后运行 ruby myapp.rb。在 Heroku 中移除端口。将 web: ruby myapp.rb 放入你的 Procfile 文件中。请注意,这不是针对 Sinatra 的回答,但我认为它简化了依赖关系。 - Chloe
14个回答

2
require 'rubygems'
require 'sinatra'

set :public_folder, File.dirname(__FILE__) + '/../client'
#client - it's folder with all your file, including myapp.rb

get "/" do
  File.read('index.html')
end

1
您可以考虑将index.html文件移动到views/index.erb,并定义一个端点,如下所示:
get '/' do
  erb :index
end

0
将文件放在public文件夹中有一个限制。实际上,当您在根路径'/'时,它可以正常工作,因为浏览器会设置相对路径,例如/css/style.css,而sinatra将在public目录中查找该文件。但是,如果您的位置是例如/user/create,那么Web浏览器将在/user/create/css/style.css中查找您的CSS文件,并且将失败。

作为解决方法,我添加了以下重定向以正确加载CSS文件:

get %r{.*/css/style.css} do
    redirect('css/style.css')
end

-7
这个解决方案怎么样?:
get "/subdirectory/:file" do 
  file = params[:file] + "index.html"
  if File.exists?(params[:file])
    return File.open("subdirectory/" + file)
  else
   return "error"
  end
end

所以,如果你现在导航到(例如)/subdirectory/test/,它将加载subdirectory/test/index.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接