我正在尝试为自定义Ruby on Rails Api创建一个管理面板。正在使用react创建管理面板。
已知
问题
在前端经过身份验证后,用户可以查看声明为"私有"的页面,但在尝试使用自定义标头向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;
&#13;
这是在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