执行Rails 5的HTTP OPTIONS请求,以进行CORS的预检或其他操作 [英] Perform HTTP OPTIONS request from Rails 5 for CORS pre-flight or otherwise

查看:59
本文介绍了执行Rails 5的HTTP OPTIONS请求,以进行CORS的预检或其他操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对Rails的拉取请求中重新添加了options方法,该方法现在应该是实时的.下面的答案将不再是必需的.调用 process(:options,path,** args)以执行选项请求.

I re-added the options method in a pull request to Rails which should now be live. The answer below should no longer be necessary. Call process(:options, path, **args) in order to preform the options request.

如果需要,请参阅commit 1f979184efc27e73f42c5d86c7f19437c6719612了解更多信息.

我已经阅读了其他答案,但是它们似乎都无法在Rails 5中使用.令人惊讶的是,Rails不仅提供了options方法,而且还提供了.当然,如果您可以使用xdomain,您可能应该(我不再持有这种观点,CORS具有优势),因为它们都更快(没有预检检查加倍延迟!),更容易(没有需要愚蠢的标头/HTTP方法!),并且得到更多的支持(基本上可以在任何地方使用!),但有时您只需要支持CORS,而CORS gem的某些功能使其不适用于您.

I've read around the other answers and none of them seemed to work in Rails 5. It's surprising that Rails doesn't just ship with an options method, but here we are. Of course if you can use xdomain, you probably should (edit: I no longer hold this view, there are advantages to CORS) because it's both faster (no preflight check doubling latency!), easier (no need for silly headers / HTTP methods!), and more supported (works basically everywhere!) but sometimes you just need to support CORS and something about the CORS gem makes it not work for you.

推荐答案

config/routes.rb 文件的顶部放置以下内容:

At the top of your config/routes.rb file place the following:

match "/example/",
  controller: "example_controller",
  action: "options_request",
  via: [:options]

然后在您的控制器中输入:

And in your controller write:

def options_request
  # Your code goes here.
end

如果您有兴趣编写集成测试,则 process 方法周围会有一些错误信息,该方法实际上不是公共方法.为了支持来自集成测试的OPTIONS请求,请创建一个初始化程序(我位于: config/initializers/integration_test_overrides.rb ,因为我重写了很多东西),并添加以下代码:

If you are interested in writing an integration test there is some misinformation around the process method, which is not actually a public method. In order to support OPTIONS requests from your integration tests create an initializer (mine is at: config/initializers/integration_test_overrides.rb because I override a number of things) and add the following code:

class ActionDispatch::Integration::Session

  def http_options_request(path)
    process(:options, path)
  end

end

以便您可以从集成测试中调用 http_options_request .

So that you can call http_options_request from your integration test.

这篇关于执行Rails 5的HTTP OPTIONS请求,以进行CORS的预检或其他操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆