无法理解cors如何使用rails
在我的routes.rb
中resources :topics
resources :test
match '/topics' => 'topics#index', :constraints => {:method => 'OPTIONS'}
match '/topics/:id' => 'topics#show', :constraints => {:method => 'OPTIONS'}
应用程序控制器中的
after_filter :set_access_control_headers
before_filter :cor
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Request-Method'] = 'POST, GET'
end
def cor
headers["Access-Control-Allow-Origin"] = "*"
headers["Access-Control-Allow-Methods"] = %w{GET POST PUT DELETE OPTIONS}.join(",")
headers["Access-Control-Allow-Headers"] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(",")
head(:ok) if request.method == 'OPTIONS'
end
在angular services.js 中
'use strict';
var services = angular.module('angapp.services', ['ngResource']);
services.factory('Topic', ['$resource', function($resource)
{
return $resource('http://localhost:port/topics.json', {},{
query: {method:'GET', params:{ port:':3000'}, isArray:true} });
}]);
services.factory('SingleTopic', ['$resource', function($resource)
{
return $resource('http://localhost:port/topics/:id.json', {id: '@id' },{
get: {method:'GET', params:{ port:':3000', id:'id'}, isArray:false }});
}]);
services.factory('multitopicloader',['Topic', '$q', function(Topic, $q){
return function() {
var delay = $q.defer();
Topic.query(function(topics){
delay.resolve(topics);
}, function() {
delay.reject('Unable to get topics');
});
return delay.promise;
};
}]);
services.factory('topicloader', ['SingleTopic','$route','$q', function(SingleTopic, $route ,$q){
return function() {
var delay = $q.defer();
SingleTopic.get({id: $route.current.params.topicID}, function(topic){
delay.resolve(topic);
}, function(){
delay.reject('unable to fetch', + $route.current.params.topicID)
});
return delay.promise;
};
}]);
每件事都很好。我根据这里的指示实施了cors Rails, Backbone, PhoneGap, CORS (not allowed by Access-Control-Allow-Origin error) 和http://www.tsheffler.com/blog/?p=428
我在这里有一些问题
当我评论或删除任何资源时:主题或匹配“/主题”它不起作用。 仅当routes.rb中存在match和resources语句时,它才有效。我不知道为什么rails需要匹配和资源声明来工作cors。(我也尝试将:constraints => {:method =>'options'}添加到资源:topic并删除match =>“/ topics”但是这是行不通的) 在rails 4中匹配函数折旧。那么我怎么能在没有'匹配'的轨道4中做到这一点
我无法清楚地了解cor和set_access_control_headers实际上做了什么。服务器是否使用cor函数中的头响应来自浏览器的初始请求作为响应,并在最终响应浏览器时响应set_access_control_headers中的头。
有人可以清楚地解释有关'cors'以及它如何与rails配合使用的'OPTIONS'。如果request.method =='OPTIONS'
,请使用此语句head(:ok)