django “http://localhost:3000”已被CORS策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

k3bvogb1  于 2023-05-30  发布在  Go
关注(0)|答案(3)|浏览(279)

我正在使用Django和React使用Rest框架进行项目。我在www.example.com中设置了CORS_ALLOW_ALL_ORIGINS=Truesettings.py,但仍然收到错误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.
我正在使用axios发布和获取请求。令人惊讶的是,即使在错误后,请求发出,但获取请求失败。这是使用axios的react文件

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()

 }
kokeuurv

kokeuurv1#

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",
]
j5fpnvbx

j5fpnvbx2#

这肯定是后端的问题,我是说Django。
CORS_ALLOW_ALL_ORIGINS=True设置CORS_ALLOW_ALL_ORIGINS值后,还需要设置ALLOWED_HOSTS的值。例如ALLOWED_HOSTS=['*']
请看下面的链接。
https://pypi.org/project/django-cors-headers/
https://dzone.com/articles/how-to-fix-django-cors-error

lvmkulzt

lvmkulzt3#

您也可以使用CORS_ALLOWED_ORIGINS限制其他网络访问您的端点;使用CORS_ALLOW_ALL_ORIGINS=True不建议仅用于生产模式。

CORS_ALLOWED_ORIGINS = [
"http://localhost:8080",
"http://localhost:5173",
"http://localhost:3000",

]

相关问题