Serving static files with Sinatra

后端 未结 14 1750
渐次进展
渐次进展 2020-11-29 16:38

I have one page website only using HTML, CSS and JavaScript. I want to deploy the app to Heroku, but I cannot find a way to do it. I am now trying to make the app working wi

相关标签:
14条回答
  • 2020-11-29 16:49

    Putting files in public folder has a limitation. Actually, when you are in the root '/' path is works correctly because the browser will set the relative path of your css file for example /css/style.css and sinatra will look for the file in the public directory. However, if your location is for example /user/create, then the web browser will look for your css file in /user/create/css/style.css and will the fail.

    As a workaround, I added the following redirection to correctly load css file:

    get %r{.*/css/style.css} do
        redirect('css/style.css')
    end
    
    0 讨论(0)
  • 2020-11-29 16:52

    Keep in mind that in production you can have your web server send out index.html automatically so that the request never gets to Sinatra. This is better for performance as you don't have to go through the Sinatra/Rack stack just to serve static text, which is what Apache/Nginx are awesome at doing.

    0 讨论(0)
  • 2020-11-29 16:53

    You can always use Rack::Static

    https://www.rubydoc.info/gems/rack/Rack/Static

    Just add this line before 'run' command into 'config.ru'

    use Rack::Static, :urls => [""], :root => 'public', :index => 'index.html'
    
    0 讨论(0)
  • 2020-11-29 16:54

    You can use the send_file helper to serve files.

    require 'sinatra'
    
    get '/' do
      send_file File.join(settings.public_folder, 'index.html')
    end
    

    This will serve index.html from whatever directory has been configured as having your application's static files.

    0 讨论(0)
  • 2020-11-29 16:54

    What about this solution? :

    get "/subdirectory/:file" do 
      file = params[:file] + "index.html"
      if File.exists?(params[:file])
        return File.open("subdirectory/" + file)
      else
       return "error"
      end
    end
    

    so if you now navigate to (for example) /subdirectory/test/ it will load subdirectory/test/index.html

    0 讨论(0)
  • 2020-11-29 16:59

    Without any additional configuration, Sinatra will serve assets in public. For the empty route, you'll want to render the index document.

    require 'rubygems'
    require 'sinatra'
    
    get '/' do
      File.read(File.join('public', 'index.html'))
    end
    

    Routes should return a String which become the HTTP response body. File.read opens a file, reads the file, closes the file and returns a String.

    0 讨论(0)
提交回复
热议问题