Cross-Origin Resource Sharing (CORS) is a way of making HTTP requests from one server to another. CORS gives the server authority of who can make requests and what type of requests are allowed. Browsers are the clients that follows CORS policies.
If you ever face this error you are trying to send cross-origin request (request that made from a host to a different host).
There are several ways to solve the Cors issue.
Way 1. You can allow any other origins(domains) to access your backend server.
If you developing in ruby on rails follow next steps :
- Install the gem:
gem install rack-cors
- Update your config/application.rb file by adding this:
config.middleware.insert_before 0, Rack::Cors do
resource '*', :headers => :any, :methods => [:get, :post, :patch, :delete, :options]
Way 2. Disable CORS in the browser.
You can directly disable CORS in the browser. For security reason disable it only while developing your website/app.
There is a great CORS extension for Chrome that allows you to run your browser with web security disabled. Add it and you will see the icon to the right of the address bar.
Make sure the icon’s label is “on” (clicking on the icon you can change Cors from ‘on’ to ‘off’). Also if you are using PATCH request in your application you might get an error that says “Patch request is not allowed by Access-Control-Allowed-Methods”. It might happen because Patch is not allowed by default. You gonna need to change the setting and include method Patch to the list. Open options page (as shown on the picture above) and manually type PACH to the allowed methods line.
Way 3. Another way how to run Chrome with Cors disable without adding any extension.
- Create a folder ‘data’ in C/Users/julia(replace with your username folder name)/Documents
- Open notepad. Copy and paste this 2 command into created file.
git cd C:\Program Files (x86)\Google\Chrome\Application
chrome.exe--user-data-dir="C:\Users\julia(replace julia with your username folder name)\Documents\data"--disable-web-security
- Save the file on your desktop(or any path you would like) as cors.bat. You can name it whatever you want, but keep the extentoin .bat
- Go to the folder where you have saved the cors.bat file (in my case it is on a desktop) and open it. Once it is done it will open a new Chrome window with disable web security. You gonna see the warning right below address bar that you are using browser with disable security.
Then again using browser with disable security is not save. Use it only while developing and never when searching the web.