djangorestreactjscorsdjango-rest-framework

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


Solution

  • Please Note: This solution is not for production configuration. This is merely a workaround for easier setup while development. Please refrain from using this in production configuration.

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