使用 React 调用 REST API 时出现 CORS 错误 [英] CORS error while consuming calling REST API with React

查看:54
本文介绍了使用 React 调用 REST API 时出现 CORS 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带有 django-rest-framework 的 restful 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.

我正在使用 fetch 调用 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"标头.因此不允许访问 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 install 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆