CodeSky 代码之空

随手记录自己的学习过程

Rails 处理跨站请求

2015-08-18 20:05分类: Ruby评论: 0

AnguarlJS中的方法虽然可以直接进行jsonp跨域请求,不用像jQuery那样包装jsonp,不过依旧需要后端开启跨域,否则仍旧没办法数据交互: 已阻止跨源请求:同源策略禁止读取位于 http://localhost:3000/create 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。

在需要的Controller或者放在application_controller里:

1	skip_before_filter :verify_authenticity_token
2
3	before_filter :cors_preflight_check
4	after_filter :cors_set_headers
5
6	# ...
7
8	def cors_preflight_check
9	  if request.method == 'OPTIONS'
10	    headers['Access-Control-Allow-Origin'] = '*'
11	    headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
12	    headers['Access-Control-Allow-Headers'] = 'Authorization,Origin,X-Requested-With,Content-Type,Accept,x-csrf-token'
13	    headers['Access-Control-Max-Age'] = '1728000'
14	    render :text => '', :content_type => 'text/plain'
15	  end
16	end
17
18	def cors_set_headers
19	  headers['Access-Control-Allow-Origin'] = '*'
20	  headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
21	  headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
22	  headers['Access-Control-Max-Age'] = '1728000'
23	end
24

这里的 skip_before_filter :verify_authenticity_token是因为POST请求时会发生: ActionController::InvalidAuthenticityToken

所以务必加上。

接着我们还需要在routes里修改,加上options的支持

1resources :articles, via: [:options]
2

后端基本上就处理完了

评论 (0)