首页 文章

rails api,反应前端,axios,CORS在开发中不起作用

提问于
浏览
0

我确信这个问题(或者非常类似的问题)已被多次询问,但我是新手来处理原始请求,并且在搜索其他人的答案时,我无法从React发送基本请求前端到只有rails-api的后端,而两者都在开发服务器上本地运行 .

任何帮助解决这个问题/帮助我理解为什么它不工作将是非常感谢!

前端:(在onClick函数处理程序上,在端口3000上的npm dev服务器上运行)

function sendGetRequest() {
    Axios.request({
        url: 'http://localhost:3001/users/2',
        method: 'get',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        withCredentials: true
    }).then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
}

后端(导轨机架,在导轨puma服务器上运行,在端口3001上):

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins 'localhost:3000'
        resource '*',
          :headers => :any,
          :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
          :methods => [:get, :post, :put, :patch, :delete, :options, :head]
      end
    end

我通过postman和rspec验证了各种控制器方法都适当地响应了JSON .

当我尝试运行此操作时,我会收到以下错误:

“无法加载http://localhost:3001/users/2:当请求's credentials mode is '包含'. Origin ' http://localhost:3000'因此不允许访问时,响应中的'Access-Control-Allow-Origin'标头的值不能是通配符'*' . 由XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制“ .

非常感谢!

1 回答

  • 0

    让我用我的应用程序使用 rack-cors 分享一些代码 .

    这是 config/initializers/cors.rb 中的代码 .

    if Rails.application.config.x.cors_allowed_origins
      Rails.application.config.middleware.insert_before 0, Rack::Cors do
        allow do
          origins Rails.application.config.x.cors_allowed_origins
    
          resource '*',
            headers: :any,
            methods: [:get, :post, :put, :patch, :delete, :options, :head],
            credentials: true
        end
      end
    end
    

    Rails.application.config.x.cors_allowed_origins 以上是通过环境变量在 config/application.rb 中设置的,以便在开发和 生产环境 时设置不同的允许来源 .

    config.x.cors_allowed_origins = ENV['CORS_ALLOWED_ORIGINS']
    

    通过这些设置,预计此应用程序将启动一个环境变量,该变量接受SPA的运行端口,如 CORS_ALLOWED_ORIGINS=localhost:8080 bundle exec rails s . localhost:8080 这是运行SPA的主机 .

    在SPA方面,这是给予 whatwg-fetch 的选项 . 很抱歉,我不在这里使用Axios,但这对您有所帮助 .

    const options = {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      mode: 'cors',
      credentials: 'include'
    };
    

相关问题