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

问题描述

尝试通过名为api"的 API 子域在 Rails 中实现 Web 服务.
在我的 hosts 文件中,我添加了一行: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

rake routes 之后,我有以下内容:

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 Length 设置为 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、子域路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:46