Answer a question

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.

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 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.

I'm not sure on how to solve this problem as i'm just starting to use React

Answers

Install django-cors-headers through pip install django-cors-headers

Then, add in installed apps 'corsheaders'.

Add the setting,

CORS_ORIGIN_ALLOW_ALL = True

and,

ALLOWED_HOSTS = ['*']

This should do the trick.

UPDATE

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',
    ...
]
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐