gpt4 book ai didi

django - 使用 React 调用 REST API 时出现 CORS 错误

转载 作者:行者123 更新时间:2023-12-03 13:33:03 25 4
gpt4 key购买 nike

我使用 django-rest-framework 创建了一个 Restful api,可通过此 URL http://192.168.33.10:8002/scenarios/ 访问我正在创建一个 React 应用程序来调用 api 并使用其数据。

我正在使用 fetch 来调用 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})
})
},

当我运行我的应用程序时,我的浏览器出现错误

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

最佳答案

请注意:此解决方案不适用于生产配置。这只是开发时更轻松设置的一种解决方法。请不要在生产配置中使用它。

通过pip install django-cors-headers安装django-cors-headers

然后,在已安装的应用程序中添加“corsheaders”。

添加设置,

CORS_ORIGIN_ALLOW_ALL = True

并且,

ALLOWED_HOSTS = ['*']

这应该可以解决问题。

更新

您还需要将其添加到中间件中,

MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]

关于django - 使用 React 调用 REST API 时出现 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44037474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com