'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

Timd Hunter picture Timd Hunter · Nov 9, 2020 · Viewed 11.5k times · Source

I am working on project using Django and React using Rest Framework. I have set CORS_ALLOW_ALL_ORIGINS=True in settings.py still i am getting error Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/encrypt/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am using axios to post and get request. Suprisingly even after error post request is made but get request fails. This is react file using axios

sendImage =()=> {
     this.activateSpinner()
     let formData = new FormData()
     formData.append('to_be_hidden', this.state.files[0], this.state.files[0].name)
     formData.append('used_to_hide', this.state.files[1], this.state.files[1].name)
     axios.post('http://127.0.0.1:8000/api/encrypt/', formData, {
         headers: {
            'accept': 'application/json',
            'content-type': 'multipart/form-data'
         }
     })
     .then(resp=>{
         this.getImageClass(resp)
         console.log(resp.data.id)
     })
     .catch(err=>{
         console.log("Code broke at send image")
         console.log(err)
     })
 }

 getImageClass =(obj)=> {
     axios.get(`http://127.0.0.1:8000/api/encrypt/${obj.data.id}/`, {
         headers: {
            'accept': 'application/json',
         }
     })
     .then(resp=>{
         this.setState({recentImage:resp})
         console.log(resp)
     })
     .catch(err=>{
        console.log("Code broke at get image")
        console.log(err)
    })
    this.deactivateSpinner()

 }

Answer

web-sudo picture web-sudo · Nov 9, 2020

It's definitely the issue from the backend side, I mean Django.

CORS_ALLOW_ALL_ORIGINS=True Once you set the CORS_ALLOW_ALL_ORIGINS value, you also need to set the values for ALLOWED_HOSTS. For instance ALLOWED_HOSTS=['*']

Please take a look at the below links.

https://pypi.org/project/django-cors-headers/

https://dzone.com/articles/how-to-fix-django-cors-error