Ionic - No 'Access-Control-Allow-Origin' header is present
Closed this issue · 3 comments
Hello
I have ionic mobile app that makes use of a Rails 5.2 api that i built myself. I'm having trouble geting a PUT request to go thru. I'm hitting this error.
Failed to load https://votingapi.herokuapp.com/api/v1/something: 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:8100' is therefore not allowed access.
I have made GET request to the API and no problems with that. Managed to fix the problem in ionic serve --lab by enabling Allow-Control-Allow-Origin: * plugin to chrome but the problem is still in the Ionic view. Also tried to set up a proxy server in the frontend with out much success.
I think the problem is regarding the options request we send to the server. At least that is when it stops working.
Is there away to fix this on the backend or is it a problem with the frontend?
localhost:8100 not being allowed access
Any thoughts?
Gemfile
gem 'rack-cors', require: 'rack/cors'
application.rb
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: %w[:get :post :put :delete :options],
expose: %w[access-token expiry token-type uid client],
max_age: 0
end
end
Request on ionic
update(id, result){
let headers = new Headers();
let body = JSON.stringify({vote: result})
headers.append("Accept" , 'application/json');
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
return this.http.put(`${this.apiUrl}/${id}`, body, options)
}
See your SO post for possible answer: https://stackoverflow.com/a/49702007/1354994
Unfortunately it didn't do the trick for us.
SOLVED
So we found a solution to this problem.
This is the change we did:
%w[:get :post :put :delete :options] => %i[get post put delete options]
Checkout: https://ionicframework.com/docs/wkwebview
They switched to this at some point on the ionic framework, and it says somewhere there that this enforces proper CORS settings compared to the previous one. So if the backend doesn’t setup cors rules appropriately it will not work
now.
we need an array of symbols for that config, and what we had was generating an array of strings
%w[:get :post :put :delete :options] returns [":get", ":post", ":put", ":delete", ":options"]
and
%i[get post put delete options] returns [:get, :post, :put, :delete, :options]
Hopefully this can help someone :)