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

在两台服务器之间实现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’)报错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值