【问题标题】:CORS with rails api 5带有rails api 5的CORS
【发布时间】:2018-06-20 22:01:28
【问题描述】:

我正在尝试使用 jquery 发送一个 post 方法

  jQuery.ajax({
      headers: { 'Authorization': "Token token=123546" },
      url: "https://paycar-public-api.herokuapp.com/api/v1/users", 
      type: "POST",
      processData: false,
      contentType: 'application/json',
      data:  
          JSON.stringify({
          email: "mikew75+123@gmail.com",

        })
  });

我明白了

无法加载https://paycar-public-api.herokuapp.com/api/v1/users: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“https://app.instapage.com” 使用权。响应的 HTTP 状态代码为 500。

我的application.rb 看起来像这样:

class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.

# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
config.api_only = true

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

API 由 heroku 托管

我不确定我是否理解它为什么不起作用,任何帮助将不胜感激。

【问题讨论】:

  • 响应的 HTTP 状态码为 500——这就是你需要解决的问题。与您的 CORS 配置无关,正在发生一些内部服务器错误,您需要首先弄清楚并修复它。检查您的服务器日志。您在该浏览器消息中看到提及 Access-Control-Allow-Origin 的唯一原因是您在应用程序代码中设置的标头不会添加到 5xx 响应中。

标签: jquery ruby-on-rails heroku


【解决方案1】:

迈克,

查看此 gem,看看它是否可以帮助您解决问题:https://github.com/cyu/rack-cors

要详细了解为什么会发生这种情况,您可以查看之前回答的一些问题:

How does Access-Control-Allow-Origin header work?

【讨论】:

  • 已安装。即使我启用了获取帖子和来自任何地方的选项,我也看不出它为什么拒绝我
  • 看起来你想通了。我也遇到了 CORS 错误,rack-cors 配置让我绕过了它。
【解决方案2】:

实际上,这是我的 rails 设置的一个简单错误。它处于暂存状态,配置有问题。

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 2016-08-20
    • 2019-04-12
    • 2015-02-06
    • 1970-01-01
    • 2017-01-13
    • 2018-12-25
    • 2017-10-08
    • 2018-03-25
    相关资源
    最近更新 更多