Connecting React Frontend with Django Backend: A Step-by-Step Guide
Machine learning enthusiast with a strong emphasis on computer vision and deep learning. Skilled in using well-known machine learning frameworks like TensorFlow , scikit-learn and PyTorch for effective model development. Familiarity with transfer learning and fine-tuning pre-trained models to achieve better results with limited data. Proficient in Python, Machine Learning, SQL, and Flask.
This guide will walk you through the process of setting up a React frontend that communicates with a Django backend in the most simplest and the minimum possible way. Let's get right in..
Frontend Setup
Initialize the Frontend Project: Start by creating a new React project using Vite, a next-generation frontend tooling. Run the following commands in your terminal:
npm create vite@latest frontend -- --template react cd frontend npm install && npm install axios react-router-domAPI Configuration: Create a file named
api.jsinside thesrcdirectory to manage API requests to the Django backend. We will use axios package in react which will help us in connecting react with django:// src/api.js import axios from 'axios'; const api = axios.create({ baseURL: 'http://127.0.0.1:8000', // Django backend URL }); export default api;Create Home Component: Add a new file named
Home.jsxinside thesrcdirectory with the following code:import { useState, useEffect } from "react"; import api from "../api"; import './App.css' const Home = () => { const [data, setData] = useState(null); useEffect(() => { api.get('/users/') .then(res => setData(res.data)) .catch(err => console.log(err)); }, []); return ( <> <h1>Home</h1> {JSON.stringify(data)} </> ); }; export default Home;App Configuration: Update
App.jsxto include routing and render theHomecomponent:// src/App.jsx import { BrowserRouter, Routes, Route } from 'react-router-dom'; import Home from './Home'; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> </Routes> </BrowserRouter> ); } export default App;
Backend Setup
Initialize the Backend Project:Open a new terminal move one dir back from the frontend dir. Create a new Django project and an app for handling user data:
django-admin startproject backend cd backend python3 manage.py startapp usersDefine Views and URLs: In
views.pyof theusersapp, define a simple view to return JSON response:# users/views.py from django.http import JsonResponse def home(request): return JsonResponse({"message": "React-Django app connected successfully"})Update
backend/urls.pyto include the view:# users/urls.py from django.urls import path from users.views import home urlpatterns = [ path('users/', home, name='users'), ]CORS Configuration: Install
django-cors-headersand configure it insettings.pyto allow cross-origin requests:pip install django-cors-headersUpdate
settings.py:INSTALLED_APPS = [ ... 'corsheaders', 'users', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = TrueDatabase Migration: Apply migrations to create necessary database tables:
python3 manage.py migrate
Run the Application
Start Development Servers: Start both frontend and backend servers:
npm run dev # Start React development serverpython3 manage.py runserver # Start Django development serverAccess Application: Open browser and navigate to
http://localhost:5173to view your React frontend. You can now interact with your application, and the React frontend will communicate with the Django backend seamlessly.
By following these steps, you've successfully connected your React frontend with a Django backend, paving the way for you to build much complex and scalable web applications.
Happy coding!