【问题标题】:How to accept PUT and DELETE methods in my Rails RESTful web service如何在我的 Rails RESTful Web 服务中接受 PUT 和 DELETE 方法
【发布时间】:2012-04-30 09:03:00
【问题描述】:

我构建了一个返回 JSON 的 Ruby On Rails 3.0.x 应用程序。到目前为止,我的广告控制器中只有四种方法:索引、显示、更新、销毁。

当我尝试从同一域中的应用程序调用方法时(通过 AJAX 和 jQuery),我成功了。但是,当我尝试从另一个域中的另一个应用程序执行相同操作时,我会收到以下错误消息,仅当我尝试使用 PUT 和 DELETE 方法时(它适用于 GET 和 POST):

XMLHttpRequest 无法加载 URL_HERE 源 URL_HERE 不允许 访问控制允许来源。

我的 RESTful 服务是通过 HTTP 而不是 HTTPS 调用的。

下面是我正在使用的 AJAX 代码(16 是广告的 id):

$.ajax({
    type: "DELETE",
    url: "http://SERVICE_URL/advertisements/16.json",
    crossDomain: true,
    success: function(response){
            alert("test");

    }
    });

有什么想法吗?

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rest jquery ruby-on-rails-3.1


    【解决方案1】:

    你可以试试rack-cors。我们为 our web service 启用 CORS:

    # config/application.rb
    config.middleware.use Rack::Cors do |requests|
      requests.allow do |allow|
        allow.origins '*'
        # perhaps you would stick :put and :delete here?
        # then you should follow the rack-cors documentation to only enable it where necessary
        allow.resource '*', :headers => :any, :methods => [:get, :post]
      end
    end
    

    【讨论】:

    • 哇,我一直在寻找这个解决方案几天,但没有任何帮助。谢谢!
    • @Seamus Abshere 嗨,我想知道为什么这些动词(PUT 和 DELETE)在默认情况下受到保护。还想知道为什么允许使用 Post 和 get 方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多