在使用React调用REST API时发生CORS错误 [英] CORS error while consuming calling REST API with React
问题描述
我使用django-rest-framework创建了一个宁静的api,可通过以下URL访问该 http://192.168.33.10:8002/scenarios/,我正在创建一个React应用,以调用api并消耗其数据.
I created a restful api with django-rest-framework accessible with this URL http://192.168.33.10:8002/scenarios/ and I'm creating a React app to make calls to the api an d consume its data.
我正在使用访存来调用api
I'm using fetch to make calls to the api
componentWillMount: function(){
this.setState({Problemstyle: this.props.Problemstyle})
fetch('http://192.168.33.10:8002/scenarios/')
.then(result=>result.json())
.then(result=> {
this.steState({items:result})
})
},
运行我的应用程序时,我的浏览器出现错误
when i run my app i get an error in my browser
Fetch API无法加载 http://192.168.33.10:8002/scenarios/.所请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许访问来源" http://192.168.33.10:8001 .如果不透明的响应可以满足您的需求,请将请求的模式设置为"no-cors",以在禁用CORS的情况下获取资源.
Fetch API cannot load http://192.168.33.10:8002/scenarios/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.33.10:8001' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我不确定如何解决此问题,因为我刚刚开始使用React
I'm not sure on how to solve this problem as i'm just starting to use React
推荐答案
通过 pip安装django-cors-headers安装django-cors-headers
然后,添加已安装的应用程序"corsheaders".
Then, add in installed apps 'corsheaders'.
添加设置,
CORS_ORIGIN_ALLOW_ALL = True
和
ALLOWED_HOSTS = ['*']
这应该可以解决问题.
更新
您还需要将其添加到中间件中,
You'll also need to add it to the middlewares,
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
这篇关于在使用React调用REST API时发生CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!