So, I've just recently put all of my frontend (React app) and backend (Django) code on GitHub and made them separate apps on Heroku. They used to be together, and therefore the React app was served from the same host and didn't give issues with the CORS policy.
But, now I keep getting a CORS error when trying to access the API (Django backend) from a subdomain on my site. The frontend is on dashboard.buildmycrm.com and the api is on buildmycrm.com.
Does anyone know what I need to put in my settings.py file in Django in order to allow the frontend to make API calls to the backend? I have regex, but I'm not sure if I used the right one.
Any help would be much appreciated!
install corsheaders
Add "corsheaders" to installed apps.
Add "CORS_ORIGIN_ALLOW_ALL = True" at the bottom of your settings.py .
Excellent tutorial on combining react and django => https://www.youtube.com/watch?v=uZgRbnIsgrA&t=5s&ab_channel=JustDjango
Thank you, I was able to figure out what I was doing wrong. In regards to "CORS_ORIGIN_ALLOW_ALL=True", as far as I understand, that's not secure for for production. I have it set to True in development, but I needed to allow only certain domains in production.
Thanks for your feedback though! I appreciate it.
You will need to install corsheader lib in django and allow all or add your frontend to the whitelist.
check out this blog for the details https://dzone.com/articles/how-to-fix-django-cors-error
That's what I ended up using. The problem I was having was I needed to update to the newest version of corsheaders and use the correct variable names. (They had changed it from CORS_ORIGIN_WHITELIST to CORS_ALLOWED_ORIGINS)
Thanks for your feedback!
Out of curiosity, why did you separate them?
My main reason was that I am starting to work in a team. I have 2 new people joining soon and I wanted a way to collaborate on the codebase. So, I decided to use GitHub and create 3 repositories. This way, when we're working on the frontend, it won't affect the backend API.
Also, having 3 separate sections (API, user dashboard, and admin dashboard) works well with Heroku's pipeline system for development. It integrates with GitHub and auto deploys each section whenever there is a change in the master branch.
Also, with Heroku, having the frontend (my frontends are in React) on it's separate dyno means I can have the Heroku buildpack run the "npm run build" script automatically whenever there is a master change.
Long story short: it streamlined everything for me and made it so much easier to work as a team.
Gotcha, that makes sense, thanks for the detailed response!