Cannot fetch data from Rails at ReactJS - ruby-on-rails

I am using front-end source is ReactJS at port 5555, and my back-end is Rails at port 8888. I was trying to fetch data from Rails at React by using:
const url = 'http://localhost:8888/problems';
fetch(url)
.then(res => {
res.json();
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
but I was received the message:
Access to fetch at 'http://localhost:8888/problems' from origin 'http://localhost:5555' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have no idea about that error. Please help me to fix it

Read more about CORS
to fix this, you need rack-cors gem in your Gemfile gem 'rack-cors'
in config/application.rb
# Rails 5
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :options]
end
end
# Rails 3/4
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :options]
end
end
that would suffice for your local right now. You will need to modify it if you deploy your code.

As comment said, this is a CORS error.
You could fix it according to this question allow-anything-through-cors-policy

Related

When I call any API is getting a response CORS error for rails API

I am trying to configure the back-end with the front-end while they are running two different ports. I send a request to it from an app (on a different subdomain than the API) I get the following response:
Access to XMLHttpRequest at 'http://localhost:3000/api/products?desc=true&tab=Competition&trending=false&page=1' from origin 'http://localhost:3001' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I don't understand why this is happening, since I have already set up Rack CORS Middleware.
CROS configuration as follows:
Gemfile:
gem 'rack-cors'
config/initializers/cors.rb:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
# TODO: add only authorized url address
origins '*'
resource '*', headers: :any, methods: [:get, :post, :patch, :put]
end
end
For reference, I have attached a browser error screenshot.
Preflight request:
Preflight response body
Ajax request :
export const fetchProducts = () => (dispatch) => {
// dispatch(requestProducts())
const data = { desc: true, tab: 'My Products', trending: false }
$.ajax({
method: 'get',
url: `http://localhost:3000/api/products?desc=true&tab=Competition&trending=false&page=1`,
// csrfToken,
xhrFields: {
withCredentials: true
},
success(response) {
console.log(response)
// dispatch(receiveProducts(response));
},
error(xhr) {
console.log(xhr)
// dispatch(receiveServerErrors(xhr));
}
})
}
Thank You
You should try to set the response header key "access-control-allow-credentials" to be true with a specific origin. Like the code below:
# config/initializers/cors.rb
require 'rack/cors'
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'http://localhost:3000'
resource '*', headers: :any, methods: [:get, :post, :patch, :put], credentials: true
end
end

AMP Access-Control-Allow-Credentials Error

I have problem After google cache my AMP page. I am implementing amp page with rails 5. Using rake-cors gem for cross-origin. Normally page working fine but after the cache is shown console error.
Error:
The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'https://www-myurl-in.cdn.ampproject.org' is therefore not allowed access.
config/application.rb
config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'https://www-myurl-in.cdn.ampproject.org'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
I don't know where I change in my code, Please help me.
After modifying Response Header its working fine.
response.headers['AMP-Redirect-To'] = request.protocol+request.host_with_port+url
response.headers['Access-Control-Expose-Headers'] = 'AMP-Redirect-To, AMP-Access-Control-Allow-Source-Origin'
response.headers['AMP-Access-Control-Allow-Source-Origin'] = params[:__amp_source_origin]

rails api, react front end, axios, CORS in development not working

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!
Let me share you with some code from my app using rack-cors.
This is the code in 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 above is set in config/application.rb via an environment variable in order to set different allowed origins on development and on production.
config.x.cors_allowed_origins = ENV['CORS_ALLOWED_ORIGINS']
With these setting, this app is expected to be launched with an environment variable which accepts the running port of SPA like CORS_ALLOWED_ORIGINS=localhost:8080 bundle exec rails s. localhost:8080 here is the host where SPA is running on.
In SPA side, this is the option given to whatwg-fetch. Sorry that I don't use Axios here, but it would be of your help.
const options = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode: 'cors',
credentials: 'include'
};

Check origin in Rails 5 API

I'm building an app with Rails 5 API. Currently, anyone sending request to my rails server can receive response.
I want to process only those requests whose origin is mydomain.com
How can I do so?
I believe you'll want to implement CORS on your API.
Simply add rack-cors gem.
And add:
#config/application.rb
config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'mydomain.com' resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
Please read carefully its documentation
You'll find very useful information there.

Ruby on Rails - AJAX request not working (cross-origin), tried everything

(sorry for bad english)
I try to execute an ajax request but it doesn't work due to same-origin policy. My application is not deployed yet and I use Ruby on Rails 3.2.3 with Unicorn server.
The AJAX request is in an asset javascript file and I call it in a view. when I try to get the datas from the AJAX requests, the console says
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url]. This can be fixed by moving the resource to the same domain or enabling CORS."
I tried everything :
Use jsonp in ajax request : console.log said syntax error
Use rack cors, with making everything said on the readme (https://github.com/cyu/rack-cors), but it didn't work, still the same message in the console (restatring server or not)
Try some syntaxes for rack-cors said on every post about it in stack overflow I could find, I tried this :
application.rb :
config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options], expose: :location
end
but it didn't work, and I tried this in config.ru
use Rack::Cors do
# allow all origins in development
allow do
origins 'localhost:3000'
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :options]
end
end
I tried this code with "origins 'localhost:3000'" ans with "origins '*'" but none of them worked, I didn't forgot the "require 'rack/cors'"
I am desperte, could you help me please ?
It is almost undoubtedly that you aren't defining the proper headers to allow access. The following walk-through should get you going:
http://dotnet-concept.com/Tip/2015/3/5798824/Cross-Origin-Request-Blocked-The-Same-Origin-Policy-disallows-reading-the-remote-resource-This-can-be-fixed-by-moving-the-resource-to-the-same-domain-or-enabling-CORS-
We had a similar situation that was resolved using rack-cors
Gemefile:
gem 'rack-cors', :require => 'rack/cors'
application.rb:
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
Don't forget to restart your rails server!
EDIT:
It just occurred to me, that this will only work in production if you are using your app server as the web server as well. If you are using Nginx or Apache as your web server, then your static assets will be served from it. You will have to enable CORS on Nginx/Apache.

Resources