How to handle non-root URLs in a singlepage app?

前端 未结 3 1534
悲&欢浪女
悲&欢浪女 2020-12-31 23:56

I try to make a single page app with Rails 3.2 and Backbone.js with pushState option but faced with something that I do not understand.

If I load the root URL of the

3条回答
  •  甜味超标
    2021-01-01 00:47

    Finally I found the solution.

    I put the following code into my routes.rb

    class XHRConstraint
      def matches?(request)
        !request.xhr? && !(request.url =~ /\.json$/ && ::Rails.env == 'development')
      end
    end
    
    match '(*url)' => 'home#index', :constraints => XHRConstraint.new
    

    With this matcher all non-XHR requests are routed to HomeController which returns an HTML page. And XHR requests will be handled by other controllers which return JSON responses. Also I left requests ending with ".json" as valid in development environment for debugging.

提交回复
热议问题