Reputation: 87
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()
}
Upvotes: 6
Views: 23865
Reputation: 190
You can also use CORS_ALLOWED_ORIGINS to restrict other networks from accessing your end points; using CORS_ALLOW_ALL_ORIGINS=True isn't advisable for production mode only.
CORS_ALLOWED_ORIGINS = [
"http://localhost:8080",
"http://localhost:5173",
"http://localhost:3000",
]
Upvotes: 0
Reputation: 686
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
Upvotes: 5
Reputation: 516
ALLOWED_HOSTS=['*']
INSTALLED_APPS = [
'django.contrib.admin',
...
'corsheaders',
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
....
"corsheaders.middleware.CorsMiddleware",
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
Upvotes: 11