I'm sure that this question (or questions very similar) has been asked many times, but I'm new to cross origin requests, and in searching through other people's answers, I haven't been able to send basic requests from a React front end to a rails-api only backend, while both are running locally on development servers.
Any help to resolve this issue/help me understand why it's not working would be really appreciated!
Front end: (as on onClick function handler, running on an npm dev server on port 3000)
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);
});
}
Backend (rails rack-cors, running on a rails puma server, on port 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
I have verified through postman and rspec that the various controller methods are all responding with JSON appropriately.
When I attempt to run this, I receive errors along the lines of:
"Failed to load http://localhost:3001/users/2: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute."
Thanks so much!
origins 'localhost:3000'line need to instead beorigins 'http://localhost:3000'(thehttp://protocol part must be included). But even once you make that change I don’t think it’s going to fix the problem that’s causing the error message in the question. The cause of that seems to be that some other part of your server code for thehttp://localhost:3001server is already sending back anAccess-Control-Allow-Origin: *response header. The server should instead be sending back anAccess-Control-Allow-Origin: http://localhost:3001response header. - sideshowbarkerlocalhost. I have a similar setup that functions correctly without 'http://'. - w_hileAccess-Control-Allow-Origin: localhost:3001response header is not going to match thehttp://localhost:3001origin the browser expects. That header value needs to be an origin, which must include the protocol. - sideshowbarkeroriginsnode in rack-cors is generically compared against the Origin header, to check whether the CORS response headers should be sent. So in this case, you can indeed specifyorigins localhost:3001- this will allow requests from bothhttp://localhost:3001andhttps://localhost:3001- roryhewitt