Api 铁路:没有路线匹配

Tel*_*imi 0 api curl ruby-on-rails

我用Sourcey教程做了一个 Rails 5 api,现在出现路由错误。

Curl 命令curl -H "Authorization: Token token=8NjQH4YVWQdUIve4xDQBaArr" http://localhost:3000/v1/users显示 404 未找到消息,并且在我的术语中,在服务器运行的情况下引发“没有路由匹配”

没有路由匹配 [GET]“/v1/users”

所以我查了一下rails routes。输出是:

v1_users GET    /v1/users(.:format)     api/v1/users#index {:subdomain=>"api"}
         POST   /v1/users(.:format)     api/v1/users#create {:subdomain=>"api"}
 v1_user GET    /v1/users/:id(.:format) api/v1/users#show {:subdomain=>"api"}
         PATCH  /v1/users/:id(.:format) api/v1/users#update {:subdomain=>"api"}
         PUT    /v1/users/:id(.:format) api/v1/users#update {:subdomain=>"api"}
         DELETE /v1/users/:id(.:format) api/v1/users#destroy {:subdomain=>"api"}
Run Code Online (Sandbox Code Playgroud)

我们注意到我们有 GET /v1/users 和 /:id

如何解决这个问题呢 ?

路线.rb:

Rails.application.routes.draw do
  constraints subdomain: 'api' do
    scope module: 'api' do
      namespace :v1 do
        resources :users
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

users_controller.rb 和 api_controller.rb 位于/app/controller/api/v1/内。

如果您需要代码的另一部分(控制器、模型......),请随时询问

max*_*max 5

问题是您的路由有子域限制。这样你的 api 就只能在http://api.example.com/v1/users.

如果不通过 apache 或 nginx 设置虚拟主机、编辑主机文件或使用Ngrok等服务,则无法将子域与 localhost 一起使用。

您也可以将其转换为路径约束:

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :users
    end
  end
end
Run Code Online (Sandbox Code Playgroud)