Question

How to solve CORS error when using DO Spaces, Django and react?

Hello, I’ve been dealing with this for the past week and can’t seem to find the root of the problem.

I have a Django API with DRF, corsheaders enabled with CORS_ORIGIN_ALLOW_ALL = True. I also have a React App on a different domain. I can make requests from my react app to my django API without any problem EXCEPT when I do a post request to upload a picture from my react app suddenly No ‘Access-Control-Allow-Origin’ error appears.

The strange thing is that when I serve my API through my local machine (localhost:8000) I suddenly get no errors, so only when serving my API in api.example.com I get the error when trying to post a picture.

For my files I use django-storages and Digital Ocean Spaces, for my api I’m using Ubuntu 18.04, nginx and gunicorn.I followed this guide to setup djnago in a DO bucket: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04.

I also have CORS enabled on my DO Spaces.

Django:

#settings.py
ALLOWED_HOSTS = ['*']
CORS_ORIGIN_ALLOW_ALL = True
INSTALLED_APPS = [
...
'storages',
'corsheaders',
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]

React

const postImagePlan = async (file: any, access: string) => {
//Creates new form data
let data = new FormData();
data.append("picture", file);
try {
const response = await axios.post(plansPictureUrl, data, {
headers: { Authorization: `JWT ${access}` },    
});
return response;  
} catch (error) {
return error;  
}};`

Digital Ocean Spaces https://preview.redd.it/49q45byt0p451.png?width=591&format=png&auto=webp&s=bd5eb8f99d17c2899cd40e0bef7b66e397fdbe15

Also, a common error is people not adding ‘/’ to the end of urls, I can confirm I am adding it.

Any info will help at this point. Thanks


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

Try the answer provided by me on this question