简体   繁体   English

在Rails服务器上设置跨域调用

[英]Setting up cross-domain calls on Rails server

I'm developing a Rails API, and a separate html5 application. 我正在开发一个Rails API和一个单独的html5应用程序。 They do not share the same domain. 他们不共享相同的域。 How do I set up my Rails application to accept cross-domain requests? 如何设置我的Rails应用程序以接受跨域请求? I have added the following to the top of my ApplicationController, but without any luck - 我已将以下内容添加到ApplicationController的顶部,但没有任何运气 -

  before_filter :set_access_control_headers

  def set_access_control_headers
    headers['Access-Control-Allow-Origin'] = 'http://myfrontend.com:3002'
    headers['Access-Control-Request-Method'] = 'GET, OPTIONS, HEAD'
    headers['Access-Control-Allow-Headers'] = 'x-requested-with,Content-Type, Authorization'
  end

My javascript on my other app looks as follows - 我在其他应用上的javascript看起来如下 -

var req = $.ajax({
  url: url,
  type: "GET",
  crossDomain: true,

  success: function(data, textStatus, jqXHR)
  {
     alert('success');
  },
  error: function(jqXHR, textStatus, errorThrown)
  {
     alert('error');
  }
});

When I run this request, I get the following in my server log - 当我运行此请求时,我在服务器日志中获得以下内容 -

Started OPTIONS "/api/search?location_uuid=22222222222222222" for 127.0.0.1 at 2013-07-15 16:49:56 -0400
Processing by Api::V1::SearchController#index as JSON
  Parameters: {"location_uuid"=>"22222222222222222"}
WARNING: Can't verify CSRF token authenticity
  User Load (20.5ms)  SELECT "users".* FROM "users" ORDER BY name DESC LIMIT 30 OFFSET 0
(63.1ms)  SELECT COUNT(*) FROM "users" 
Completed 204 No Content in 300ms (ActiveRecord: 0.0ms)

Anyone have any tips in getting this to work correctly? 任何人都有任何提示让这个正常工作?

It seems that adding the data-type as JSONP avoids the cross browser problems: 似乎将数据类型添加为JSONP可以避免跨浏览器问题:

var req = $.ajax({
  url: url,
  type: "GET",
  crossDomain: true,
  dataType: "JSONP",
  ...

See this question for more info - 有关详细信息,请参阅此问题 -

Can anyone explain what JSONP is, in layman terms? 用外行人的话可以解释一下JSONP是什么吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM