Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 358
ChemseddineZ Avatar asked May 18 '17 02:05

ChemseddineZ


People also ask

How do I fix CORS error in REST API?

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.

How resolve CORS error in react with core in asp net?

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!


Video Answer


1 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',
    ...
]
like image 54
zaidfazil Avatar answered Oct 27 '22 21:10

zaidfazil