When you are doing frontend development, it is almost inevitable to encounter CORS issues at some moment, in this quick guide, I will briefly explain how can you solve this problems.
I'm not going to explain in this post what CORS is or how it works, I'll save that for later.
Depending on your configuration and the frameworks you are using, you can solve your issue with one of the next options, but some times (like in my case), you need to use both options to get it working.
Run chrome using --disable-web-security
flag:
The first option works in most cases, you can simply open your terminal and run google-chrome-stable --disable-web-security
to open chrome. Before running the command, make sure to kill all chrome instances.
In order to run de command successfully, you need to specify a data directory for the session, I recommend using the tmp
folder, this way all testing data should be wiped once you restart your computer.
The full command should looks similar to:
google-chrome-stable --disable-web-security --user-data-dir="tmp"
Now you can navigate to your site and test if the CORS error is gone, if not, you can try the next option.
Use a proxy
If the first option didn't worked, you will need a way to bypass CORS restrictions, the most efficient way to do it is using a proxy, in my case, I'm using local-cors-proxy.
I recommend to install it globally, that way you don't contaminate your projects and you can use it in all your projects without updating package.json
.
- Install globally
npm install -g local-cors-proxy
- Start proxy
lcp --proxyUrl https://localhost:8000
- That's it, your CORS error is gone!.
This is the "least invasive to the codebase" way that I have found to solve this, this way you don't have to modify nothing in your backend nor in your frontend and you can continue developing without any issue.
I hope this helped.