我在Rails中开发了一个API,我想通过api.domain.com
访问它。在本地,我修改了/etc/hosts
文件,因此domain.com
和api.domain.com
都解析为localhost。对于暂存和制作,我为api.domain.com
和api.staging.domain.com
创建了CNAME别名,以指向各自的服务器domain.com
和staging.domain.com
。
在我的routes.rb
中,我所有的api路径都嵌套在
namespace :api, path: '/', defaults: { format: 'json' }, constraints: { subdomain: 'api' } do
当我向api.domain.com
发出请求时,本地工作正常。但是当我尝试对生产和登台服务器执行相同操作时,我的请求失败,说它无法匹配路由,例如:
ActionController::RoutingError (No route matches [GET] "/v1/users/2/likes"):
actionpack (4.1.4) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
actionpack (4.1.4) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
railties (4.1.4) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.1.4) lib/rails/rack/logger.rb:20:in `block in call'
activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `block in tagged'
activesupport (4.1.4) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `tagged'
railties (4.1.4) lib/rails/rack/logger.rb:20:in `call'
actionpack (4.1.4) lib/action_dispatch/middleware/request_id.rb:21:in `call'
rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
rack (1.5.2) lib/rack/runtime.rb:17:in `call'
activesupport (4.1.4) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
rack (1.5.2) lib/rack/lock.rb:17:in `call'
actionpack (4.1.4) lib/action_dispatch/middleware/static.rb:64:in `call'
rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
railties (4.1.4) lib/rails/engine.rb:514:in `call'
railties (4.1.4) lib/rails/application.rb:144:in `call'
rack (1.5.2) lib/rack/commonlogger.rb:33:in `call'
rack (1.5.2) lib/rack/chunked.rb:43:in `call'
rack (1.5.2) lib/rack/content_length.rb:14:in `call'
unicorn (4.8.3) lib/unicorn/http_server.rb:576:in `process_client'
unicorn (4.8.3) lib/unicorn/http_server.rb:670:in `worker_loop'
unicorn (4.8.3) lib/unicorn/http_server.rb:525:in `spawn_missing_workers'
unicorn (4.8.3) lib/unicorn/http_server.rb:140:in `start'
unicorn (4.8.3) bin/unicorn:126:in `<top (required)>'
答案 0 :(得分:4)
这个怎么样?
# inline
constraints: { subdomain: /api(?:\.(staging))?/ }
# config/routes.rb
# API Routes
constraints subdomain: /api(?:\.(staging))?/ do
...
end
以上内容符合:api.example.com
,api.staging.example.com
您也可以轻松地将其他人添加到此,例如
# config/routes.rb
# API Routes
constraints subdomain: /api(?:\.(staging|other))?/ do
...
end
上述内容符合:api.example.com
,api.staging.example.com
,api.other.example.com