首页 文章

Rails CORS问题与Ajax API endpoints 请求

提问于
浏览
0

我似乎遇到了向API endpoints 发出GET请求的一些问题 . 我知道rails在幕后有一些安全性 . 我正在使用React-Rails并在我的 componentDidMount 中对API endpoints 进行ajax调用 . 我也在我的 Headers 中传递 X-Auth-Token .

我的控制台错误:

XMLHttpRequest无法加载“/ api / end / point ...”对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头 . 因此不允许来源'http:// localhost:3000'访问 . 响应具有HTTP状态代码401 .

我的ajax电话看起来像

$.ajax({ url: "my/api/endpoint...", headers: {"X-Auth-Token": "My API token..."},
    success: (response) => { console.log(response); } })

1 回答

  • 0

    因为您的前端将从任何来源(任何客户端)执行请求,您必须从任何来源启用CORS . 尝试

    # config/initializers/cors.rb
    Rails.application.config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*',
          headers: :any,
          methods: [:get, :post, :put, :patch, :delete, :options, :head]
      end
    end
    

    我在rails 5 api应用程序中使用它 . 在rails 5之前,将 rack-cors gem添加到 Gemfile . 无论如何,重启你的服务器 .

    铁轨3/4

    # config/application.rb
    module YourApp
      class Application < Rails::Application
    
        config.middleware.insert_before 0, "Rack::Cors" do
          allow do
            origins '*'
            resource '*', :headers => :any, :methods => [:get, :post, :options]
          end
        end
      end
    end
    

相关问题