试图通过称为“api”的API子域在rails中实现web服务。
在我hosts
文件我加入一行:127.0.0.1 api.localhost
Rails 4,子域路由
在我routes.rb
我设置子域名,在这里我只需要指数的行动和几个手动添加宁静的路线,通过如下:
namespace :api, path: '', :constraints => {:subdomain => "api"} do
resources :posts, only: :index do
collection do
get 'popular_by_day'
get 'popular_by_week'
end
end
end
也产生了coresponding控制器:rails g controller api/posts
试验例:
class Api::PostsController < ApplicationController
def index
@posts = 1
respond_to do |format|
format.json { render :json => @posts }
end
end
def popular_by_day
end
def popular_by_week
end
end
rake routes
后我有以下:
popular_by_day_api_posts GET /posts/popular_by_day(.:format) api/posts#popular_by_day {:subdomain=>"api"}
popular_by_week_api_posts GET /posts/popular_by_week(.:format) api/posts#popular_by_week {:subdomain=>"api"}
api_posts GET /posts(.:format) api/posts#index {:subdomain=>"api"}
所以,据我所知,链接http://api.localhost:3000/posts应该工作,但我得到的路由错误:
没有路由匹配[GET] “/帖”(同与/posts.json)
你可以尝试改变127.0.0.1 api.localhost线为127.0.0.1 api.localhost.local? – Slawek
再次出现同样的错误 – Srle