I am trying to build a React - Rails API project. I added gem 'rack-cors'
and created the config/initializers/cors.rb
file:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins "http://localhost:3001"
# The React part will be on port 3001 so thats way we add it
# Change it to the production url when going on production
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
I would only like to allow the port 3001
since thats the port my React front-end will be served at.
Now I would like to test if this is actually working and blocking other requests.
Up until now, I have been using Postman
to test the API (had to download it to work with http
). I thought that because I added the filter to only a specific port, it would block the requests from Postman
but it is still showing the data requested in the API call.
Also if I try reaching it like this on the browser:
http://localhost:3000/api/v1/users
It is still giving the data, which should be blocked to every port except 3001
.
Why is it happening? Is there any other way to double check if it is working? Thanks!
NOTE: I killed the server and restarted it again and it is still behaving the same
CodePudding user response:
Make an API call from browser (Not from URL and Not from postman). May be through ajax to test.
Postman does not implement the CORS restrictions
CodePudding user response:
To test CORS locally, I found this repo: https://github.com/njgibbon/nicks-cors-test
Just clone it, and click on the html
file so it opens in your browser. By default it is calling the github API
(https://api.github.com) and fetching info from there. You can open the console and check it.
If you change it to https://google.com
it will throw a CORS restriction.
Similarly, you can change it to http://localhost:3000/api/v1/users
(in my case) and it will throw a CORS error with the config I have now.
To double-check, just go to cors.rb
and put origins "*"
. Restart the app server and try running again the html file. Now we won't be blocked.