javascriptpythonreactjsdjangoaxios

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


Solution

  • 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