2016-12-14 107 views
0

我做了一个rails 5 API与Sourcey教程,现在我得到一个路由错误。Api轨道:没有路线匹配

卷曲命令curl -H "Authorization: Token token=8NjQH4YVWQdUIve4xDQBaArr" http://localhost:3000/v1/users显示404未找到的消息和“无路由匹配”在我的术语被升高,其中在服务器运行

无路由匹配[GET]“/ V1 /用户”

所以我检查了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"} 

我们注意到我们有GET/V1 /用户/:ID

如何解决这个问题呢?

routes.rb中:

Rails.application.routes.draw do 
    constraints subdomain: 'api' do 
    scope module: 'api' do 
     namespace :v1 do 
     resources :users 
     end 
    end 
    end 
end 

Users_controller.rb和api_controller.rb是内部/应用/控制器/ API/V1/

如果您需要的代码的另一部分(控制器,模型....)不要犹豫,问

回答

4

的问题是,你的路线有一个子域约束。所以你的api只能在http://api.example.com/v1/users

你不能没有通过Apache或nginx的设置虚拟主机,修改hosts文件或使用服务像Ngrok与本地主机使用子域名。

你也可以将其转换为路径约束,而不是:

Rails.application.routes.draw do 
    namespace :api do 
    namespace :v1 do 
     resources :users 
    end 
    end 
end 
+0

非常感谢!我有理由让范围模块:'API'做',我没有添加'名称空间'API'做'使用卷曲与URL http://api.example.com/v1/users – Tellimi

+0

是啊,这只是如果你想要而不是http:// example.com/api/v1/users'。如果您设置了一个隧道,以便您可以使用子域访问您的Rails服务器,则无需更改路由。 – max