【问题标题】:CORS not working on Rails 6 with React frontend on different portsCORS 无法在不同端口上使用 React 前端的 Rails 6 上运行
【发布时间】:2021-04-22 05:10:23
【问题描述】:

http://localhost:3000(通过rails s)上运行rails 6.1.1 开发服务器
http://localhost:3001 上响应客户端(通过yarn start

我已经尝试了以下

在 gemfile 中,gem 'rack-cors' 和捆绑安装

config/intializers/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

application.rb

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

来自 react js 客户端的示例 axios 请求

axios.post('http://localhost:3000/users', {user}, {withCredentials: true})
      .then(response => {
    ...
     })
      .catch(error => console.log('api errors:', error))
    };

还尝试用127.0.0.1 替换localhost,在配置中添加http://,但没有一个解决方案有效

响应错误说被 CORS 政策阻止

Access to XMLHttpRequest at 'http://localhost:3000/users' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

【问题讨论】:

    标签: ruby-on-rails reactjs axios cors ruby-on-rails-6


    【解决方案1】:

    如果您已经设置了config/initializers/cors.rb,则无需在application.rb中添加配置

    遇到了同样的问题,我对cors.rb 的设置如下:

    Rails.application.config do |config|
      config.middleware.insert_before 0, Rack::Cors do
        allow do
          origins '*'
          resource '*', headers: :any, methods: [:get, :post, :patch, :put]
        end
      end
    end
    
    

    但是,这就是我创建 axios 请求的方式(请注意标头部分):

    let service = axios.create({
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*' <=== notice this header here
      },
      baseURL: process.env.VUE_APP_API_PATH
    });
    service.interceptors.response.use(this.handleSuccess, this.handleError);
    this.service = service;
    

    并像这样使用它:

    this.service.request({
          method: 'POST',
          url: path,
          responseType: 'json',
          data: payload
        }).then((response) => {
          return { status: response.status, data: response.data };
        });
    

    【讨论】:

      猜你喜欢
      • 2019-06-29
      • 2023-04-07
      • 2018-09-21
      • 1970-01-01
      • 2021-05-22
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      相关资源
      最近更新 更多