Categories

Thursday, November 21, 2024
#919814419350 therichposts@gmail.com
DjangoPythonReactjsReactjs Tutorial

Django Remove Cors Error and Show Json Data in React Application

Django Remove Cors Error and Show Json Data in React Application

Hello guys how are you? Welcome back on my blog Therichpost. Today in this post I am going to tell you how to Django Remove Cors Error and Show Json Data in React Application?

live demo
Django Remove Cors Error and Show Json Data in React Application
Django Remove Cors Error and Show Json Data in React Application

Guys for more Django and React stuff please click on them.

Guys here is the code snippet and please use carefully:

1. Guys now we need to run below commands to get cors headers package into our Django project:

pip install django-cors-headers

2. Guys now we need to add below code inside mysite/settings.py to set the cors issue for api:

...
INSTALLED_APPS = [
    ...
    'corsheaders'
]

MIDDLEWARE = [
   ...
     'corsheaders.middleware.CorsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
...

3. Guys here is my react application code to get and show django api json data:

import React, { useEffect } from "react"
function App() {
  useEffect(() => {
    const url = "http://127.0.0.1:8000/daily";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        console.log(json);
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchData();
}, []);
  return (
    <div className='App'>
    </div>
  );
}

export default App;

This is it guys and if you will have any kind of query, suggestion and requirement then please do comment below.

I have just shown you basic things and further more you can set this free project according to your reequipments.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.