请求的资源上不存在“Access-Control-Allow-Origin”标头
我在AngularJS上使用omniauth-facebook并且CORS无法正常工作。
我的omniauth.rb是
Rails.application.config.middleware.use OmniAuth::Builder do provider :facebook,"xxxxx", "xxxxx", :scope => 'email,user_birthday,read_stream', :display => 'popup' end
如果我将它用作rails应用程序和请求,一切正常。 但是当我尝试通过Angular JS调用’http:\ localhost:3000 \ users \ auth \ facebook“时
$http.get('/users/auth/facebook').success(function(data, status, headers, config) { console.log("back in success"); }). error(function(data, status, headers, config) { }); }
我在JS控制台中看到以下错误
XMLHttpRequest无法加载https://www.facebook.com/dialog/oauth?client_id=xxxx&display=popup … thday%2Cread_stream&state = 3352c1924bdbc9277f7b1070c38d67acf79b529f198323cb。 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此不允许
'http://localhost:3000'
访问。
(该控制台中的url未完全显示)
我添加了以下行
config.middleware.insert_before Warden::Manager, Rack::Cors
但这也行不通。
什么是最好的方式或如何覆盖OmniAuth的标头?
我正在使用Angularjs和gem devise,omniauth-facebook
由于您处于开发环境中,因此您可能希望通过允许浏览器以非安全模式运行来尝试解决方法。
对于Windows上的Chrome,请从CMD尝试:
> cd C:\Program Files (x86)\Google\Chrome\Application > chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
--disable-web-security
标志将允许您发出跨域请求。 --user-data-dir
标志将允许您仅为开发打开新会话。
这只是您开发工作的一种解决方法 ! 不要在生产中使用它或导航到此会话中的其他站点!
问题是Javascript无法进行跨域请求。 这样做是出于安全原因,因此脚本无法调用远程服务器并暴露敏感数据。
下面是一个非常简单的解释的链接,其中包含一些如何解决它的选项:
http://developer.yahoo.com/javascript/howto-proxy.html
这里有一个先前的答案,它也有一些很好的信息:
为什么我在这里看到“Access-Control-Allow-Origin不允许来源”错误?
如果他们没有设置标题,那么你不能强迫他们拥有标题。 也许你应该看看使用JSONP 。 但是,通过服务器进行镜像并不是那么糟糕,因为每次访问最多只能处理一次,而且很可能每个用户一次,因为很少有人删除cookie。
在服务器中设置’Access-Control-Allow-Origin’将进行跟踪。 喜欢: ruby headers['Access-Control-Allow-Origin'] = '*'
在rails中。
问题是您从https
安全站点获取数据是您的站点的http
到http
因此最新的浏览器不支持交叉允许来源。
唯一的解决方案是让您的网站支持https
。
在您的ApplicationController.rb中添加
def set_access_control_headers headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' end
对于CORS,您必须将要从服务器端的跨源请求访问的域列入白名单
headers['Access-Control-Allow-Origin'] = '*' //star will allow all the domain you can specify also which url u want to access
在客户端,您必须将config()中的标头设置为
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
有时因浏览器而出现问题。默认情况下,允许跨域请求。 在chrome中,您需要添加一个“Allow-Control-Allow-Origin:*”插件并启用它。