Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

django - CORS error while consuming calling REST API with React

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...