我正在尝试为自定义Ruby on Rails Api创建一个管理面板 . 正在使用react创建管理面板 .

The Known

  • Ruby on rails api正在使用devise来处理用户身份验证

  • 能够从localhost使用auth endpoints 登录,没有任何问题

  • api使用Rack-Cors自述文件中显示的基本设置启用了cors

  • auth endpoints 返回用于身份验证的必要标头

  • 表示 Headers 保存在前端反应应用程序的会话中

The Problem

在前端经过身份验证后,用户可以查看声明为“私有”的页面,但是当尝试使用自定义标头向api发出get请求时,我收到CORS错误 . 以下是收到的错误 .

Failed to load http://localhost:3001/vehicles: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这是发出请求的代码 .

class VehicleApi {
  static getAllVehicles(authHeaders) {
    console.log(authHeaders);
    const myInit = { method: 'GET',
               headers: {
                 'Content-Type': 'application/json',
                 'access-token': authHeaders.accessToken,
                 'token-type': authHeaders.tokenType,
                 'client': authHeaders.client,
                 'expiry': authHeaders.expiry,
                 'uid': authHeaders.uid
               },
               mode: 'cors',
               cache: 'default' };
    return fetch('http://localhost:3001/<endpoint>', myInit).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }
}

export default VehicleApi;

这是api上的cors设置 .

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