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
To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard. For more information on configuring CORS for REST APIs, see Configuring CORS for a REST API resource. For HTTP APIs, see Configuring CORS for an HTTP API.
Just install allow CORS browser extension for your respective browser. And turn it on while making API requests. You will not get any errors, also you don't need to change anything in your code!
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',
...
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With