Wildcard matching for Rails API Versioning causes infinite redirect

眉间皱痕 提交于 2019-12-13 14:50:25

问题


I was following the excellent solution posted here regarding versioning an API using Rails routing, but I keep running into an infinite redirect.

Here is a section of my routes.rb

  namespace :api do

    namespace :v1 do
      resources :books
    end

    namespace :v2 do
      resources :books
    end

    match 'v:api/*path', :to => redirect("/api/v2/%{path}")
    match '*path', :to => redirect("/api/v2/%{path}")

  end

which is virtually the same as the posted answer. Accessing /api/v1/books/list.json works as expected as does api/v2/books/list.json. The issue I'm having is with /api/books/list.json, which should redirect to /api/v1/books/list.json. If I try to access the api without specifying which version, my browser responds with an infinite redirect. My logs look like this:

Started GET "/api/books/list.json?max_number=10" for 127.0.0.1 at 2013-04-01 22:00:51 -0400


Started GET "/api/v1/books%2Flist" for 127.0.0.1 at 2013-04-01 22:00:51 -0400


Started GET "/api/v1/books%2Flist" for 127.0.0.1 at 2013-04-01 22:00:51 -0400


Started GET "/api/v1/books%2Flist" for 127.0.0.1 at 2013-04-01 22:00:51 -0400

//... and so on

回答1:


Don't know why Ryan Biggs answer in the posted question doesn't work anymore, but this is what I changed it to in order to solve it:

  namespace :api do

    namespace :v1 do
     resources :books do
      collection do
       get 'list'
       get '/*path', :to => redirect("http://localhost:3000")
      end
     end
    end

    namespace :v2 do
     resources :books do
      collection do
       get 'list'
      end
     end
    end


  match 'v:api/*path', :to => redirect{|params, req|
    "/api/v1/#{params[:path]}.#{params[:format]}#{params[:query_string]}?#{req.query_string}"
  }
  match '*path', :to => redirect{|params, req|
    "/api/v1/#{params[:path]}.#{params[:format]}#{params[:query_string]}?#{req.query_string}"
  }
end


来源:https://stackoverflow.com/questions/15754941/wildcard-matching-for-rails-api-versioning-causes-infinite-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!