Skip to content
Advertisement

How to manage CORS in Django

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement