How to manage CORS in Django

Question:

Im trying to connect React.js[axios] and Django [hosting in Heroku] and every time I get this.
On my localhosts everything works fine I get all the object except images, but all works fine.
enter image description here

Ive allowed my host to connect but it doesn’t work

CORS_ALLOW_ORIGINS = [
    'localhost',
    'https://itbookcom.herokuapp.com/'
]

CSRF_TRUSTED_ORIGINS = [
    'localhost',
    'https://itbookcom.herokuapp.com/'
]

and here is react.js connection part

constructor(props) {
        super(props);

        this.state = {
            bookList: [],
            error: null,
        };
    }
    refreshList = () => {
        axios
            .get('https://itbookcombackend.herokuapp.com/api/books/')
            .then((res) => this.setState({ bookList: res.data }))
            .catch((err) => console.log(err));
    };

    componentDidMount() {
        this.refreshList();
    }

[GitHub – Front-End][2]
[2]: https://github.com/namra004/ITBooK

[GitHub – Back-End][3]
[3]:https://github.com/namra004/ITBookBackEnd

Asked By: Arman Nikoyan

||

Answers:

You can allow all for debugging case(DO NOT use this at production):
In your View you can add this

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt

In settings.py

CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
Answered By: leo

You can try whitelisting the origin

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
    'localhost',
    'https://itbookcom.herokuapp.com/'
]
Answered By: Pranav Patel

I was having the same issue and resolved it successfully. I wrote a step-by-step blog regarding the same. Here is the link you can refer to.

Whenever there is a CORS origin Header issue, it simply means that the server and client are not known to each other (unknown request sent to the server).

For resolving this issue you can use the following steps

pip install django-cors-headers // this will install cors header package

Add/Update this in you setting files

ALLOWED_HOSTS = ['127.0.0.1','localhost','your_domain']

And in the django middleware file section add the below code

MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...

]

By doing this the issue would be resolved.

It is mostly due to the CORS origin blockage for security purposes.

Answered By: Nikhil