Ruby on Rails 5 api subdomain
為了要 demo api subdomain 的頁面是否能夠運作,這邊用鷹架隨便建立個東西。
1 | rails g scaffold api::v1::books title |
使用 constraints 限制 subdomain: 'api'
。
然後用 scope module: 'api'
加上 app/controllers/api 這個資料夾。
1 | # config/routes.rb |
現在用瀏覽器去 http://api.localhost:3000/v1/books
頁面,會跳出 Routing Error 的錯誤。可是使用 rake routes
觀察的路徑卻是正確的。
1 | # rake routes |
要解決這個錯誤,有兩個方法:
用
lvh.me
,去瀏覽http://api.lvh.me:3000/v1/books
就能運作了。lvh.me
通常用來測試本地的網頁程式,解析的網址會是127.0.0.1
可以用來測試 subdomain。在
config/environments/development.rb
調整config.action_dispatch.tld_length = 0
預設為 1。然後去查看https://api.localhost:3000/v1/books
頁面。
tld 是指 top level domain,以下是比較 tld_length
的差別:
1 | # config.action_dispatch.tld_length = 1 |