PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to manage CORS in Django

 October 13, 2022     axios, django, javascript, python, reactjs     No comments   

Issue

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

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
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing