Home > Net >  How to manage CORS in Django
How to manage CORS in Django

Time:08-21

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

CodePudding user response:

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

CodePudding user response:

You can try whitelisting the origin

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
    'localhost',
    'https://itbookcom.herokuapp.com/'
]
  • Related