微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

“ http:// localhost:3000”已被CORS策略阻止:所请求的资源上没有“ Access-Control-Allow-Origin”标头

如何解决“ http:// localhost:3000”已被CORS策略阻止:所请求的资源上没有“ Access-Control-Allow-Origin”标头

我正在使用Django进行项目,并使用Rest Framework进行React。我在settings.py中设置了CORS_ALLOW_ALL_ORIGINS=True,但仍然收到错误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发布并获取请求。出人意料的是,即使在发出错误发布请求后,但get请求失败。 这是使用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}/`,}
     })
     .then(resp=>{
         this.setState({recentimage:resp})
         console.log(resp)
     })
     .catch(err=>{
        console.log("Code broke at get image")
        console.log(err)
    })
    this.deactivateSpinner()

 }

解决方法

这绝对是后端的问题,我的意思是Django。

Balance设置了CORS_ALLOW_ALL_ORIGINS=True的值后,还需要设置CORS_ALLOW_ALL_ORIGINS的值。 例如 ALLOWED_HOSTS

请查看以下链接。

ALLOWED_HOSTS=['*']

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。