Rails 4,子域路由 [英] Rails 4, subdomain routing

查看:75
本文介绍了Rails 4,子域路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试通过称为"api"的API子域在Rails中实现Web服务.
我在 文件中添加了以下行: 127.0.0.1 api.localhost

Trying to implement web service in rails through API sub-domain called "api".
In my hosts file i added line: 127.0.0.1 api.localhost

在我的 routes.rb 中,我设置了子域,在这里我只需执行索引操作,并通过以下操作手动添加了一些宁静的路由:

In my routes.rb i set sub-domain, where i only need index action and few manually added restful routes, through following:

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

还生成了具有以下内容的核心响应控制器: rails g controller api/posts

Also generated coresponding controller with: 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

耙路之后,我有以下内容:

After rake routes i have following:

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" 相匹配(与/posts.json相同)

So far as i know, link to http://api.localhost:3000/posts should work but i get routing error:
No route matches [GET] "/posts" (Same with /posts.json)

推荐答案

所以我要发布有关该主题的研究

So I'm posting my research on the topic

默认情况下,Rails的TLD长度设置为1.结果,它将无法确定 api.localhost 中的子域,因此会确定路由错误.

By default, Rails has its TLD Length set to 1. As a result, it won't be able to determine the subdomain in api.localhost, hence, the routing error.

您有几种解决方案:
-设置指向127.0.0.1且tld长度为1的正确域(例如dev-mywebsite.com)
-使用lvh.me
-在您的development.rb环境文件中设置 config.action_dispatch.tld_length = 0

希望这可以帮助有同样需求的其他人

Hope this helps other people in the same need

使用 localhost 实际上不是一个好主意,因此将api设置为开发中的域.我发现它不适用于跨子域的Cookie

It is actually not a good idea to use localhost so setup an api as a domain in development. I found out that it doesn't work with cookies across subdomains

这篇关于Rails 4,子域路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆