【问题标题】:Angular2 and Rails backend integrationAngular2 和 Rails 后端集成
【发布时间】:2016-01-27 20:15:42
【问题描述】:

我正在使用 angular2/http 模块开发一个非常简单的 angular 2 应用程序来访问 rails 资源。我正在运行节点开发服务器和 Rails 开发服务器。我遇到的问题是绕过 same origin policy 对 Rails 后端的 ajax 调用的限制。

错误:

XMLHttpRequest cannot load http://localhost:3000/people.
Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.

我的服务器正在运行

http://localhost:8080 //node
http://localhost:3000 //rails

我需要澄清这是如何工作的:

  1. 如果我在同一个端口上运行这些服务会发生冲突吗?
  2. 如果您必须在不同的域上运行,您如何安全地执行此操作?
  3. 当服务器几乎肯定会在不同的端口/域上时,管理员如何在生产模式下处理此问题?

【问题讨论】:

标签: ruby-on-rails json angular


【解决方案1】:

Langley 的第二个链接出现了一个很棒的 Rails 模块来管理 CORS。

Github rack-cors Gem

只需将其包含在您的 Gemfile 中,并将以下内容添加到您的 config/application.rb

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多