Rails 4 + angularjs CORS - 跨域实现的办法

mot

在两台服务器之间实现angularjs app与rails的REST api通讯,一般会遇到CORS警告的报错。
CORS Cross-origin resource sharing 其实是一种浏览器技术,定义了服务器资源是否允许被另外一个域名下地服务器读取。

添加路由options方法

要实现跨域 首先要在路由中配置:

ymlmatch 'customers', to: 'customers#index', via: [:options]
resources :users
````
然后查看你的路由 应该是这样:
```ruby
   Prefix Verb    URI Pattern               Controller#Action
    users OPTIONS /customers(.:format)          customers#index
          GET     /customers(.:format)          customers#index
          POST    /customers(.:format)          customers#create
 new_user GET     /customers/new(.:format)      customers#new
edit_user GET     /customers/:id/edit(.:format) customers#edit
     user GET     /customers/:id(.:format)      customers#show
          PATCH   /customers/:id(.:format)      customers#update
          PUT     /customers/:id(.:format)      customers#update
          DELETE  /customers/:id(.:format)      customers#destroy
     root GET     /                             customers#index

这里第二行有个options的方式

添加 before_filter 和 after_filter , 启用CORS

rubyCustomersController < ApplicationController

  skip_before_filter :verify_authenticity_token
  before_filter :cors_preflight_check
  after_filter :cors_set_access_control_headers

  # For all responses in this controller, return the CORS access control headers.
  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    headers['Access-Control-Max-Age'] = "1728000"
  end

  # If this is a preflight OPTIONS request, then short-circuit the
  # request, return only the necessary headers and return an empty
  # text/plain.

  def cors_preflight_check
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version'
    headers['Access-Control-Max-Age'] = '1728000'
  end

  def index
    @customers = Customer.all

    respond_to do |format|
      format.json { render :json => @customers }
    end
  end
end

我们添加skip_before_filter :verify_authenticity_token是为了跳过rails的422(‘Can’t verify CSRF token authenticity’)报错

阅读 12.5k

404 Page Not Found
if (is.ie) { window.location.href="config/error.htm"; }
1.2k 声望
16 粉丝
0 条评论
1.2k 声望
16 粉丝
文章目录
宣传栏