2013-11-20 145 views
3

试图通过称为“api”的API子域在rails中实现web服务。
在我hosts文件我加入一行:127.0.0.1 api.localhostRails 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)

+0

你可以尝试改变127.0.0.1 api.localhost线为127.0.0.1 api.localhost.local? – Slawek

+0

再次出现同样的错误 – Srle

回答

7

尝试http://api.lvh.me:3000为Rails 3+

Ryan Bates's railscasts

If we go to http://lvh.me:3000/ we’ll see the homepage of our application because lvh.me resolves to the IP address 127.0.0.1. The difference is that we can now prepend any subdomain we like to the URL and it will still point to the same application.

编辑:我很想知道为什么谁downvoted这个答案这样做。这种方法继续为我工作。

编辑II:从ASCII蒙上更新链接到Rails的粪补充说明Rails的3+

+0

链接已损坏。 asciicasts.com是一个控股页面。尝试http://railscasts.com/episodes/221-subdomains-in-rails-3?view=asciicast – PhilT

+0

还应该注意的是,这是Rails 3 – PhilT

7

所以我张贴我的研究的话题

默认情况下,Rails有其TLD长度集为1.因此,它将无法确定api.localhost中的子域,因此,路由错误。

您有几种解决方案:
- 建立指向与1(例如dev-mywebsite.com)
顶级域名长度为127.0.0.1一个正确的域 - 使用lvh.me
- 设置config.action_dispatch.tld_length = 0在您development.rb enrironment文件

希望这有助于同样需要

编辑其他人: 它实际上是不使用localhost这样设置的API为开发域是一个好主意。我发现它不适用于跨子域的Cookie

+0

这仍然在2018年工作 –

2

@Srle看来,我昨天遇到了这个问题。

只要尝试添加“.com”到您的子域:api.localhost.com

在我的应用程序,它的工作还有:api.myapplication-dev.com.

主要的原因是,有没有.localhost域,这样就把。COM到你的主机:)

希望它为你的工作对我来说

+0

我们可以做的另一种方法是:'api.local.host' :) –