Brolly Academy | Full Stack Development
How to Connect Backend and Frontend
Step-by-Step Guide with Code (2026)
A hands-on 2026 guide for students and beginner developers: how the frontend and backend talk through APIs, a complete React + Node.js example with code, fetch vs axios, fixing CORS, adding a database, the same connection in Python, Java, PHP, Angular and Next.js, login tokens, deployment on Vercel and Render, and the 10 errors beginners hit most.
How to connect backend and frontend step by step: REST APIs, fetch and axios, CORS, a React + Node.js + MongoDB example, Python, Java, deployment and common errors.
By Brolly Academy Team · Brolly Academy · Updated 12 November 2026

Table of Contents
1. How do frontend and backend work together?
2. What you need before you start
3. Step 1: Build the backend API (Node.js + Express)
4. Step 2: Call the API from the frontend (React + fetch)
5. fetch vs axios: which should you use?
7. Step 4: Connect frontend, backend and database
8. How to connect frontend and backend in Python (Flask and Django)
9. How to connect backend to frontend in Java Spring Boot
10. Other stacks: HTML, PHP, Angular and Next.js
11. Secure the connection: login tokens and safe APIs
12. Deploy: connect the live frontend to the live backend
13. 10 common errors when connecting frontend and backend (and fixes)
14. Best practices for clean frontend-backend connections
Quick answer
To connect backend and frontend, you build an API on the backend (a set of URLs such as /api/students that return JSON), run it on a server, and call those URLs from the frontend with fetch or axios. The frontend sends an HTTP request (GET to read, POST to create, PUT or PATCH to update, DELETE to remove), the backend runs its logic, talks to the database, and sends back a JSON response that the frontend shows on the page. If the two run on different addresses, you also allow the frontend's address on the backend with CORS.
- The connector: an HTTP API, usually REST with JSON
- Frontend side: fetch() (built into browsers) or the axios library
- Backend side: a framework such as Express (Node.js), Flask or Django (Python), Spring Boot (Java) or Laravel (PHP)
- Most common blocker: a CORS error, fixed on the backend, not the frontend
- In production: store the backend URL in an environment variable, never hard-code localhost
Key takeaways
- The frontend never talks to the database directly. It talks to the backend API, and only the backend talks to the database.
- Every connection is a request and a response: method, URL, headers, body, then a status code and JSON back.
- Start the backend first, test it in the browser or Postman, then connect the frontend.
- CORS errors are solved on the backend by allowing the frontend's origin.
- Use environment variables for the API URL so the same code works on your laptop and in production.
1. How do frontend and backend work together?
Short answer: The frontend is what runs in the user's browser; the backend is a program on a server. They work together through HTTP requests: the frontend asks, the backend answers with data, and the frontend updates the screen.
If you are new to these terms, our guide to what a full stack developer is explains front end, back end and full stack roles. Here we focus only on the connection.
Here is what happens when a user opens a page that lists students:
- Browser: the React page loads and runs fetch("http://localhost:4000/api/students")
- Network: the browser sends an HTTP GET request to that URL
- Backend: Express receives the request on the /api/students route
- Database: the backend asks MongoDB (or MySQL, PostgreSQL) for the student records
- Response: the backend sends back JSON such as [{"id":1,"name":"Ravi"}] with status 200
- Screen: the frontend reads the JSON and renders the list
What is used to connect frontend and backend?
An API connects them. In most web apps it is a REST API: a list of URLs (called endpoints) where each combination of URL and HTTP method does one job. Data travels as JSON, a simple text format both JavaScript and every backend language can read.
Which HTTP methods do you need?
The status code tells the frontend what happened. MDN's HTTP status code reference lists them all; the ones you will see most are 200, 201, 400 (bad input), 401 (not logged in), 404 (wrong URL) and 500 (server error).
2. What you need before you start
Short answer: Install Node.js (with npm), a code editor such as VS Code, and a browser. For the database step, create a free MongoDB Atlas cluster or install MongoDB locally. Postman or the VS Code Thunder Client extension helps you test the API.
- Node.js and npm: runs the Express backend and the Vite React frontend
- VS Code: open the project folder and use two terminals, one for each side
- Basic JavaScript: variables, functions, async/await and arrays
- An API tester: Postman, Thunder Client or simply the browser for GET requests
Project folder structure for the example:
student-app/
server/ (backend: Node.js + Express)
client/ (frontend: React + Vite)
Keeping the two in separate folders makes it clear which code runs where, and lets you deploy them separately later.
3. Step 1: Build the backend API (Node.js + Express)
Short answer: Create an Express app with two routes, GET /api/students and POST /api/students, turn on JSON parsing with express.json(), and start it on port 4000. Test it in the browser before touching the frontend.
Open a terminal in server/ and run:
npm init -y
npm install express cors
In server/package.json, add "type": "module" so you can use import. Then create server/index.js:
import express from "express";
import cors from "cors";
const app = express();
app.use(cors({ origin: "http://localhost:5173" })); // allow the React dev server
app.use(express.json()); // read JSON request bodies
const students = [{ id: 1, name: "Ravi", course: "Full Stack" }];
app.get("/api/students", (req, res) => {
res.json(students);
});
app.post("/api/students", (req, res) => {
const { name, course } = req.body;
if (!name || !course) {
return res.status(400).json({ error: "name and course are required" });
}
const student = { id: students.length + 1, name, course };
students.push(student);
res.status(201).json(student);
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`API running on http://localhost:${PORT}`));
Start it with node index.js and open http://localhost:4000/api/students in the browser. You should see [{"id":1,"name":"Ravi","course":"Full Stack"}]. If you do, your backend works. The Express hello world guide shows the same basic pattern.
Why port 4000?
Any free port works. We avoid 5000 because macOS uses it for AirPlay Receiver on many machines, which causes confusing "port in use" errors. The React dev server from Vite uses 5173 by default.
Test the POST route
In Postman or Thunder Client, send a POST to http://localhost:4000/api/students with this JSON body and the header Content-Type: application/json:
{ "name": "Priya", "course": "MERN" }
You should get status 201 and the new student back. Sending an empty body should return status 400 with the error message.
4. Step 2: Call the API from the frontend (React + fetch)
Short answer: In React, call the API inside useEffect to load data when the page opens, and call it from a form handler to send data. Store the backend URL in a Vite environment variable named with the VITE_ prefix.
Create the frontend in the project root:
npm create vite@latest client -- --template react
cd client
npm install
Create client/.env:
VITE_API_URL=http://localhost:4000
Vite only exposes variables that start with VITE_ to your browser code, as its env and mode guide explains. Restart the dev server after changing .env.
Replace client/src/App.jsx with:
import { useEffect, useState } from "react";
const API_URL = import.meta.env.VITE_API_URL;
export default function App() {
const [students, setStudents] = useState([]);
const [name, setName] = useState("");
const [course, setCourse] = useState("");
const [error, setError] = useState("");
useEffect(() => {
fetch(`${API_URL}/api/students`)
.then((res) => {
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
})
.then(setStudents)
.catch((err) => setError(err.message));
}, []);
async function addStudent(e) {
e.preventDefault();
setError("");
const res = await fetch(`${API_URL}/api/students`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, course }),
});
const data = await res.json();
if (!res.ok) return setError(data.error);
setStudents((prev) => [...prev, data]);
setName("");
setCourse("");
}
return (
<main>
<h1>Students</h1>
{error && <p style={{ color: "red" }}>{error}</p>}
<ul>
{students.map((s) => (
<li key={s.id}>{s.name} ({s.course})</li>
))}
</ul>
<form onSubmit={addStudent}>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" />
<input value={course} onChange={(e) => setCourse(e.target.value)} placeholder="Course" />
<button type="submit">Add student</button>
</form>
</main>
);
}
Run npm run dev in client/, open http://localhost:5173, and you should see Ravi in the list. Add a student with the form and it appears straight away. Your backend and frontend are now connected.
What each part does
- useEffect(..., []): runs the GET request once when the component first appears. React's guide on synchronizing with effects explains this pattern.
- res.ok: fetch does not throw on 404 or 500, so you must check the status yourself. MDN's Using the Fetch API guide covers this in detail.
- Content-Type: application/json and JSON.stringify: without these, Express cannot read req.body.
- Updating state with the response: the UI shows the saved record, including the id the server created.
How to connect backend and frontend in VS Code
Open the student-app folder in VS Code, open two terminals with the split-terminal button, run node index.js in server/ and npm run dev in client/. Both must stay running while you work. Many developers add nodemon to the backend so it restarts on every save.
5. fetch vs axios: which should you use?
Short answer: fetch is built into every modern browser and needs no install; axios is a small library that parses JSON automatically, throws on error status codes and makes interceptors (for adding tokens) easy. Both connect frontend and backend equally well.
The same POST with axios:
import axios from "axios";
const api = axios.create({ baseURL: import.meta.env.VITE_API_URL });
const { data } = await api.post("/api/students", { name, course });
setStudents((prev) => [...prev, data]);
The axios documentation covers instances, interceptors and error handling. For a small project, fetch is enough; for an app with login tokens on every request, axios saves time.
6. Step 3: Fix CORS errors
Short answer: A CORS error means the browser blocked the response because the backend did not allow the frontend's origin (protocol + domain + port). Fix it on the backend by allowing that origin, for example with the cors middleware in Express, or avoid it in development with a Vite proxy.
The error usually looks like this in the browser console:
Access to fetch at 'http://localhost:4000/api/students' from origin
'http://localhost:5173' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
localhost:5173 and localhost:4000 are different origins because the ports differ. Browsers block such cross-origin responses unless the server sends the right headers. MDN's CORS guide explains the rules, including the "preflight" OPTIONS request browsers send before some POST, PUT and DELETE calls.
Fix 1: allow the origin on the backend (recommended)
import cors from "cors";
app.use(cors({
origin: ["http://localhost:5173", "https://your-app.vercel.app"],
credentials: true, // only if you send cookies
}));
Put app.use(cors(...)) before your routes. The Express cors middleware page lists every option.
Fix 2: use the Vite dev proxy (development only)
// client/vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
proxy: { "/api": "http://localhost:4000" },
},
});
Now the frontend calls fetch("/api/students") and Vite forwards it to port 4000, so the browser sees a single origin. The Vite server options page documents server.proxy. This only works with npm run dev; in production you still need CORS or a same-domain setup.
What does not fix CORS
- Adding mode: "no-cors" to fetch: the request is sent, but you cannot read the response
- Adding CORS headers in the frontend code: the browser only trusts headers from the server
- Using origin: "*" with cookies: browsers reject that combination; list the exact origin instead
7. Step 4: Connect frontend, backend and database
Short answer: The frontend stays exactly the same. You only change the backend so its routes read and write a database instead of an array. Here we use MongoDB with Mongoose; the same idea works with MySQL or PostgreSQL.
Install the packages in server/:
npm install mongoose dotenv
Create server/.env (never commit this file):
MONGODB_URI=mongodb+srv://user:password@cluster0.example.mongodb.net/studentdb
Update server/index.js:
import "dotenv/config";
import express from "express";
import cors from "cors";
import mongoose from "mongoose";
await mongoose.connect(process.env.MONGODB_URI);
const Student = mongoose.model("Student", new mongoose.Schema({
name: { type: String, required: true },
course: { type: String, required: true },
}));
const app = express();
app.use(cors({ origin: process.env.CLIENT_ORIGIN || "http://localhost:5173" }));
app.use(express.json());
app.get("/api/students", async (req, res) => {
const students = await Student.find();
res.json(students);
});
app.post("/api/students", async (req, res) => {
try {
const student = await Student.create(req.body);
res.status(201).json(student);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`API running on port ${PORT}`));
MongoDB returns _id instead of id, so change the React list key to key={s._id}. Everything else in the frontend works unchanged. That is the point of an API: the frontend does not care which database sits behind it. The Mongoose documentation covers schemas and queries, and MongoDB's Node.js driver docs cover connection strings.
The full flow, frontend to database
8. How to connect frontend and backend in Python (Flask and Django)
Short answer: In Python, you build the API with Flask or Django, return JSON, and enable CORS with the flask-cors package or django-cors-headers. The React frontend code stays the same; only the backend URL changes.
Flask
pip install flask flask-cors
from flask import Flask, jsonify, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app, origins=["http://localhost:5173"])
students = [{"id": 1, "name": "Ravi", "course": "Full Stack"}]
@app.get("/api/students")
def list_students():
return jsonify(students)
@app.post("/api/students")
def add_student():
data = request.get_json()
if not data or not data.get("name") or not data.get("course"):
return jsonify(error="name and course are required"), 400
student = {"id": len(students) + 1, **data}
students.append(student)
return jsonify(student), 201
if __name__ == "__main__":
app.run(port=4000, debug=True)
The Flask-CORS documentation shows per-route and app-wide options. FastAPI works the same way with its built-in CORSMiddleware; our Pydantic AI with FastAPI guide shows a FastAPI app in practice.
Django
Install django-cors-headers, then in settings.py:
INSTALLED_APPS = [
# ...
"corsheaders",
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware", # place it near the top
"django.middleware.common.CommonMiddleware",
# ...
]
CORS_ALLOWED_ORIGINS = ["http://localhost:5173"]
A simple JSON view:
from django.http import JsonResponse
def list_students(request):
return JsonResponse([{"id": 1, "name": "Ravi"}], safe=False)
For larger APIs, most teams use Django REST Framework. If you are preparing for Django roles, see our Django interview questions.
9. How to connect backend to frontend in Java Spring Boot
Short answer: In Spring Boot, create a @RestController that returns objects (Spring converts them to JSON), and allow the frontend origin with @CrossOrigin or a global CORS configuration.
@RestController
@RequestMapping("/api/students")
@CrossOrigin(origins = "http://localhost:5173")
public class StudentController {
private final List<Student> students =
new ArrayList<>(List.of(new Student(1, "Ravi", "Full Stack")));
@GetMapping
public List<Student> all() {
return students;
}
@PostMapping
public ResponseEntity<Student> add(@RequestBody Student input) {
Student saved = new Student(students.size() + 1, input.name(), input.course());
students.add(saved);
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
}
}
record Student(int id, String name, String course) {}
Set server.port=4000 in application.properties, run the app, and the same React code connects to it. Spring's guide on enabling CORS for a REST service shows the global configuration option. For production, you would add Spring Data JPA and a database such as MySQL. Our Spring Boot course covers this end to end.
10. Other stacks: HTML, PHP, Angular and Next.js
Short answer: The pattern never changes: backend exposes URLs that return JSON, frontend calls them. Only the syntax differs by stack.
Plain HTML and JavaScript
You do not need React to connect to a backend. Plain JavaScript in an HTML page works:
<ul id="list"></ul>
<script>
fetch("http://localhost:4000/api/students")
.then((res) => res.json())
.then((students) => {
document.getElementById("list").innerHTML =
students.map((s) => `<li>${s.name}</li>`).join("");
});
</script>
Without JavaScript at all, a classic HTML form can send data to the backend: <form action="http://localhost:4000/api/students" method="post">. The browser submits the form and loads the server's response as a new page. This is how older server-rendered sites work, but you cannot update part of the page without JavaScript. Our Express example only reads JSON, so to accept a plain form post, also add app.use(express.urlencoded({ extended: true })) to the backend.
PHP
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: http://localhost:5173");
$students = [["id" => 1, "name" => "Ravi", "course" => "Full Stack"]];
echo json_encode($students);
Save it as api/students.php, serve it with php -S localhost:4000, and fetch http://localhost:4000/api/students.php from the frontend. Frameworks such as Laravel give you routing, validation and database models on top of the same idea.
Angular
Angular has its own HttpClient. Register it with provideHttpClient() in app.config.ts, then inject it in a service:
import { HttpClient } from "@angular/common/http";
import { inject, Injectable } from "@angular/core";
@Injectable({ providedIn: "root" })
export class StudentService {
private http = inject(HttpClient);
getStudents() {
return this.http.get<{ id: number; name: string }[]>("http://localhost:4000/api/students");
}
}
Angular's HttpClient guide covers setup, interceptors and error handling.
Next.js
Next.js can hold the backend inside the same project with route handlers. Create app/api/students/route.js:
export async function GET() {
return Response.json([{ id: 1, name: "Ravi" }]);
}
The frontend then calls fetch("/api/students"). Because both live on the same domain, you do not need CORS. Next.js also lets server components fetch data directly on the server.
MERN stack summary
In a MERN app, MongoDB stores data, Express and Node.js form the backend API, and React is the frontend, exactly the example in sections 3 to 7. Our MERN stack course builds several projects on this pattern.
11. Secure the connection: login tokens and safe APIs
Short answer: For logged-in users, the backend issues a token (often a JWT) after login, and the frontend sends it with every request in the Authorization header or an httpOnly cookie. The backend checks the token before returning private data.
The flow:
- Frontend sends email and password to POST /api/login over HTTPS
- Backend checks the password hash and returns a token
- Frontend stores the token and sends it on every request
- Backend verifies the token and returns 401 if it is missing or invalid
Sending the token with axios:
api.interceptors.request.use((config) => {
const token = localStorage.getItem("token");
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
The jwt.io introduction to JSON Web Tokens explains how the token is signed and verified.
Security checklist
- Use HTTPS in production so tokens and passwords are encrypted in transit
- Prefer httpOnly cookies for tokens when possible; scripts cannot read them, which limits damage from cross-site scripting. If you use cookies across origins, set credentials: "include" in fetch and credentials: true with an exact origin in CORS
- Validate every input on the backend, even if the frontend already validates it
- Never put secrets in frontend code or VITE_ variables. Anything in the frontend bundle is public. Database passwords and API keys belong only in backend environment variables
- Return clear status codes: 400 for bad input, 401 for not logged in, 403 for not allowed
12. Deploy: connect the live frontend to the live backend
Short answer: Deploy the backend first (for example on Render), copy its public URL, set it as VITE_API_URL in the frontend host (for example Vercel), add the frontend's live domain to the backend's CORS list, and redeploy both.
Step-by-step deployment
- Push both folders to GitHub. Keep .env files out of the repository with .gitignore.
- Backend on Render: create a Web Service from the repository, set the root directory to server, the build command to npm install, and the start command to node index.js. Add MONGODB_URI and CLIENT_ORIGIN as environment variables. Render's web services documentation explains ports and health checks; your code already reads process.env.PORT.
- Copy the backend URL, for example https://student-api.onrender.com, and test /api/students in the browser.
- Frontend on Vercel: import the repository, set the root directory to client, and add VITE_API_URL=https://student-api.onrender.com as an environment variable. Vercel's environment variables guide shows where to set it.
- Redeploy the frontend. Vite writes VITE_ values into the bundle at build time, so changing the variable needs a new build.
- Update CORS: set CLIENT_ORIGIN on the backend to your Vercel domain, such as https://student-app.vercel.app, and redeploy the backend.
Deployment problems to expect
- Mixed content: an HTTPS frontend cannot call an HTTP backend. Use the HTTPS URL your host gives you.
- Free-tier sleep: some free backend plans pause when idle, so the first request after a while is slow. Check your host's current free-tier rules.
- localhost in production: if the live site still calls localhost:4000, the environment variable was missing at build time.
- MongoDB Atlas network access: allow your backend host's IP addresses (or the access list your host recommends) in Atlas, or the connection will time out.
13. 10 common errors when connecting frontend and backend (and fixes)
Short answer: Most connection problems come from the backend not running, the wrong URL or port, CORS, a missing JSON parser, or environment variables that were not loaded.
A quick debugging routine
- Open the API URL directly in the browser or Postman. If that fails, the problem is the backend.
- Open the browser's DevTools Network tab. Check the request URL, method, status and response.
- Read the backend terminal for errors.
- Only then change the frontend code.
14. Best practices for clean frontend-backend connections
Short answer: Keep all API calls in one place, use environment variables for URLs, handle loading and error states, version your API, and document your endpoints.
- One API module: put all calls in src/api.js instead of scattering fetch across components
- Loading and error states: show a spinner while waiting and a clear message on failure
- Consistent JSON shape: for example, always return { error: "message" } on failures
- API versioning: prefix routes with /api/v1 so you can change them later without breaking old clients
- Document endpoints: a simple README table, or OpenAPI/Swagger for bigger projects
- Test the API separately: automated API tests catch backend bugs before the frontend sees them. Our API testing training covers Postman and automation.
- Real-time features: for chat or live dashboards, add WebSockets (for example Socket.IO) alongside your REST API
REST vs GraphQL vs WebSockets
Start with REST. Move to GraphQL or WebSockets only when the project needs them.
15. Practice projects to master the connection
Short answer: Build three small full stack projects, each adding one new connection skill: CRUD with a database, login with tokens, and a deployed app with real-time updates.
- Student manager (CRUD): React + Express + MongoDB with list, add, edit and delete. Skills: all four HTTP methods, status codes and state updates.
- Notes app with login: add signup, login and JWT-protected routes so each user sees only their notes. Skills: authentication, the Authorization header and 401 handling.
- Live order board: deploy the API on Render and the frontend on Vercel, and add Socket.IO so new orders appear without refresh. Skills: deployment, environment variables, CORS in production and WebSockets.
Put each on GitHub with a README that explains the architecture and lists the API endpoints. Recruiters for full stack roles look for exactly this. For salary expectations once you are job-ready, see our full stack developer salary and MERN stack developer salary guides.
16. How Brolly Academy helps
Short answer: Brolly Academy's 4-month Full Stack Developer course in Hyderabad teaches front-end, back-end, databases and deployment together, so you build and connect real applications with a trainer who has 15+ years in full stack development.
Our Full Stack Developer Course in Hyderabad covers everything in this guide in depth. Here is what the course page lists (November 2026):
- Duration: 4 months, in 4 practical stages, in the classroom or live online
- Technologies: HTML, CSS, JavaScript, React, Node.js, Java, Spring Boot, Hibernate, MongoDB, MySQL, Git, Docker and AWS
- Trainer: Mr. Rehan, Full Stack Specialist and Cloud Architect with 15+ years of experience
- Projects: portfolio-ready capstone projects that apply front-end, back-end and database skills, published on GitHub
- Tools: testing and debugging with Jest, Postman and Chrome DevTools, plus AI coding assistants such as ChatGPT and GitHub Copilot
- Fees: recorded learning ₹9,999, live online ₹19,999 and classroom training ₹29,999, with EMI options
- Eligibility: no previous coding experience needed
- Career support: GitHub portfolio, ATS-friendly resume, mock interviews and placement assistance
Prefer one stack? See our MERN stack course or Python full stack training. You can attend a free demo class before you enrol.
Build and connect real full stack apps with a mentor
Join a free demo of Brolly Academy's 4-month Full Stack Developer course in Hyderabad. Learn React, Node.js, Java, Spring Boot, MongoDB, MySQL and cloud deployment with Mr. Rehan (15+ years), build GitHub-ready projects, and get placement assistance. Plans start at ₹9,999 with EMI.
Frequently asked questions
How do you connect frontend and backend?
You connect them through an API. The backend exposes URLs, such as /api/students, that return JSON. The frontend calls those URLs with fetch or axios using HTTP methods like GET and POST, then displays the response. If they run on different origins, the backend must allow the frontend's origin with CORS.
How does frontend and backend work together?
The frontend runs in the browser and handles what users see. When it needs data, it sends an HTTP request to the backend. The backend checks the request, reads or writes the database, and returns JSON with a status code. The frontend then updates the page with that data.
Which is used to connect frontend and backend?
An API is used, most often a REST API that sends JSON over HTTP. On the frontend, the browser's built-in fetch function or the axios library sends the requests. On the backend, a framework such as Express, Django, Flask, Spring Boot or Laravel defines the API routes.
How to connect backend and frontend in React?
Store the backend URL in an environment variable such as VITE_API_URL, call the API with fetch or axios inside useEffect to load data, and call it from form handlers to send data. Update React state with the response. Make sure the backend allows the React dev server's origin, usually http://localhost:5173.
How to connect frontend and backend using an API?
Define API endpoints on the backend, each with a URL and HTTP method, for example GET /api/students and POST /api/students. Test them in a browser or Postman. Then call the same endpoints from the frontend, send JSON with a Content-Type header for POST requests, and handle the status code and JSON response.
How to connect frontend, backend and database?
The frontend talks only to the backend API, and only the backend talks to the database. For example, React sends a POST request to Express, Express validates the data and saves it to MongoDB with Mongoose, then returns the saved record as JSON. The frontend never stores database passwords or connects to the database directly.
How to connect backend and frontend in the MERN stack?
Build an Express and Node.js API connected to MongoDB with Mongoose, allow the React origin with the cors middleware, and call the API from React with fetch or axios. In development, run the backend on one port and the React dev server on another, or use the Vite proxy so both appear on one origin.
How to connect backend to frontend using axios?
Install axios, create an instance with axios.create and a baseURL set to your backend URL, then call api.get or api.post. Axios parses JSON automatically into res.data and throws an error for 4xx and 5xx status codes. Use an interceptor to attach a login token to every request.
What is the difference between fetch and axios?
Fetch is built into browsers and needs no installation, but you must parse JSON manually and check res.ok because it does not throw on 404 or 500. Axios is a library that parses JSON automatically, throws on error status codes, supports interceptors and has a simple timeout option. Both work well.
How do I fix a CORS error between frontend and backend?
Fix it on the backend. In Express, use the cors middleware with the frontend's exact origin, such as http://localhost:5173, and place it before your routes. In development you can also use the Vite proxy. Adding no-cors mode or headers in the frontend does not solve it, because browsers only trust the server's headers.
How to connect frontend and backend in Python?
Build the API with Flask, Django or FastAPI and return JSON. Enable CORS with flask-cors, django-cors-headers or FastAPI's CORSMiddleware, allowing the frontend's origin. The frontend, whether React or plain JavaScript, then calls the Python API URLs with fetch or axios exactly as it would call a Node.js backend.
How to connect a Django backend to a React frontend?
Create JSON views or a Django REST Framework API, install django-cors-headers, add it to INSTALLED_APPS and near the top of MIDDLEWARE, and list the React origin in CORS_ALLOWED_ORIGINS. Run Django and the React dev server, then call the Django endpoints from React with fetch or axios.
How to connect backend to frontend in Java Spring Boot?
Create a class annotated with @RestController that returns Java objects, which Spring converts to JSON. Allow the frontend origin with @CrossOrigin or a global CORS configuration. Run the app on a port such as 4000, then call its endpoints from React or Angular with fetch, axios or HttpClient.
How to connect backend and frontend in HTML?
In a plain HTML page, add a script that calls fetch with the backend URL and inserts the JSON results into the page. Without JavaScript, an HTML form with an action URL and method="post" can also send data to the backend, but the browser then loads a new page instead of updating part of the current one.
How to connect backend to frontend in Angular?
Register HttpClient with provideHttpClient in your app configuration, inject HttpClient into a service, and call methods such as http.get and http.post with your backend URL. Subscribe to the result in a component or use the async pipe. The backend must allow the Angular dev server's origin with CORS.
How to connect backend to frontend in Next.js?
Next.js can host the backend in the same project using route handlers in the app/api folder, for example app/api/students/route.js exporting a GET function that returns JSON. The frontend calls fetch("/api/students"), and because both share one domain, no CORS setup is needed. Next.js can also call external APIs from server components.
How to connect backend and frontend in VS Code?
Open the project folder containing both the client and server folders, split the integrated terminal into two, start the backend in one terminal and the frontend dev server in the other. Keep both running. Extensions such as Thunder Client let you test API endpoints inside VS Code before connecting the frontend.
How to connect backend to frontend on Vercel?
Deploy the backend first on a host such as Render, then add its public HTTPS URL as an environment variable like VITE_API_URL in your Vercel project settings. Redeploy the frontend so the value is built in, and add the Vercel domain to the backend's CORS allowed origins. Alternatively, use Next.js route handlers on Vercel itself.
Can the frontend connect directly to the database?
It should not. Putting database credentials in frontend code makes them public, because anyone can read the browser bundle. The frontend should call a backend API, which checks permissions and then talks to the database. Managed services such as Firebase use special security rules to make limited direct access safe.
Why is my req.body undefined in Express?
Express does not parse JSON bodies by default. Add app.use(express.json()) before your routes, and make sure the frontend sends the header Content-Type: application/json with a JSON.stringify body. Without either part, req.body stays undefined or empty and validation fails.
Why does my frontend show "Failed to fetch"?
Failed to fetch usually means the request never got a usable response: the backend is not running, the URL or port is wrong, CORS blocked the response, or an HTTPS page called an HTTP API. Check the browser's Network tab and console, and open the API URL directly to confirm the backend is reachable.
What is the best way to connect frontend and backend?
For most web apps, a REST API returning JSON is the best and simplest way. Keep all API calls in one frontend module, store the backend URL in an environment variable, handle loading and error states, and allow only your real frontend origins in CORS. Add GraphQL or WebSockets only when the project needs them.
How do I send a login token from frontend to backend?
After login, the backend returns a token, often a JWT. The frontend sends it with each request in the Authorization header as Bearer token, or the backend sets it in an httpOnly cookie. With cookies across origins, use credentials: "include" in fetch and allow credentials with an exact origin in CORS.
Is connecting frontend and backend hard for beginners?
Not once you understand the request and response cycle. Most beginners struggle with CORS, wrong URLs and environment variables rather than the concept itself. Building one small project, such as a student list with React and Express, usually makes the whole connection clear within a few days of practice.
Does Brolly Academy teach how to connect frontend and backend?
Yes. Brolly Academy's 4-month Full Stack Developer course covers front-end, back-end, databases and deployment with React, Node.js, Java, Spring Boot, MongoDB and MySQL, taught by Mr. Rehan with 15+ years of experience. Students build GitHub portfolio projects. Plans start at ₹9,999, and a free demo class is available.
Learn with Brolly Academy
Review the syllabus, practical projects and batch timings, and book a free demo before you enrol.
Related Articles
Continue Your Learning
Full Stack Developer Course in Hyderabad
HTML, CSS, JavaScript, React, Node.js, Java, Spring Boot, databases and cloud deployment with real projects.
View CourseMERN Stack Course in Hyderabad
MongoDB, Express, React and Node.js with full stack projects.
View CoursePython Full Stack Training in Hyderabad
Python, Django, front-end and databases for full stack roles.
View Course