A Java full stack developer builds both halves of an application: a Spring Boot REST API on the server and a React interface in the browser. Most beginners learn each half separately and then get stuck when they try to connect them. This guide shows how to make a React app talk to a Spring Boot API, step by step, and how to fix the errors almost everyone hits the first time.
How the two halves fit together
- Spring Boot runs on the server (by default on port 8080) and exposes REST endpoints such as
GET /api/studentsthat return JSON. - React runs in the browser (a Vite dev server usually uses port 5173) and calls those endpoints with
fetchor a library such as Axios. - Data travels as JSON in both directions, and HTTP status codes tell the front end whether a request worked.
Step 1: build a small REST API in Spring Boot
Start with one resource. This controller lists students and adds a new one:
@RestController
@RequestMapping("/api/students")
public class StudentController {
private final StudentRepository repo;
public StudentController(StudentRepository repo) {
this.repo = repo;
}
@GetMapping
public List<Student> all() {
return repo.findAll();
}
@PostMapping
public ResponseEntity<Student> create(@RequestBody Student student) {
return ResponseEntity.status(HttpStatus.CREATED).body(repo.save(student));
}
}Test it first with a browser or Postman: http://localhost:8080/api/students should return a JSON list. Never debug the front end until the API works on its own.
Step 2: allow the React app to call the API (CORS)
Browsers block a page on one origin (localhost:5173) from reading responses from another origin (localhost:8080) unless the server allows it. This is CORS. Allow your front end’s origin in Spring Boot:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}Allow only the origins you actually use. Avoid allowing every origin in production. If you use Spring Security, also enable CORS in the security configuration with http.cors(Customizer.withDefaults()), or the browser’s preflight request will be rejected before it reaches your controller.
Step 3: fetch the data in React
Keep the API address in an environment variable, so you can change it for production without editing code. In a Vite project, create a .env file with VITE_API_URL=http://localhost:8080, then:
import { useEffect, useState } from "react";
const API = import.meta.env.VITE_API_URL;
export default function Students() {
const [students, setStudents] = useState([]);
const [error, setError] = useState("");
useEffect(() => {
fetch(API + "/api/students")
.then((res) => {
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
})
.then(setStudents)
.catch((err) => setError(err.message));
}, []);
if (error) return <p>Could not load students: {error}</p>;
return (
<ul>
{students.map((s) => (
<li key={s.id}>{s.name}</li>
))}
</ul>
);
}Note the res.ok check: fetch does not throw on a 404 or 500 response, so you must check the status yourself.
Step 4: send data with a POST request
async function addStudent(name, email) {
const res = await fetch(API + "/api/students", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, email }),
});
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
}The Content-Type: application/json header matters. Without it, Spring Boot cannot read the body into your @RequestBody object and returns 415 Unsupported Media Type.
An alternative in development: the Vite proxy
Instead of configuring CORS while developing, you can let the Vite dev server forward API calls to Spring Boot, so the browser sees only one origin:
// vite.config.js
export default defineConfig({
plugins: [react()],
server: {
proxy: { "/api": "http://localhost:8080" },
},
});Then call fetch("/api/students") without the full address. This only applies to development, so you still need a plan for production.
Common errors and what they mean
- “blocked by CORS policy”: the origin is not allowed in Spring Boot, or Spring Security is rejecting the preflight request.
- 404 Not Found: the path in React does not match the mapping in the controller. Check
/apiprefixes and spelling. - 415 Unsupported Media Type: the
Content-Type: application/jsonheader is missing on a POST or PUT. - 400 Bad Request: the JSON field names do not match the Java class, or validation failed.
- “Unexpected token < in JSON”: the response was an HTML error page, not JSON. Usually the URL is wrong.
- Connection refused: the Spring Boot application is not running, or it runs on a different port.
Open the browser’s developer tools, go to the Network tab and click the failing request. The status code and response body usually tell you exactly which of these it is.
Moving to production
- Run
npm run buildto produce static files for the React app. - Either serve those files from the same domain as the API (so CORS is not needed), or deploy them separately and allow that exact domain in your CORS configuration.
- Set
VITE_API_URLto the production API address before building. - Use HTTPS for both, and never put passwords or secret keys in front-end code, because anyone can read it.
A portfolio project idea
Build a student management app: Spring Boot with Spring Data JPA and MySQL for the API, and React for the interface, with list, add, edit and delete screens, form validation and clear error messages. Put the API and front end in one GitHub repository with a README that explains how to run both. It shows an interviewer the whole full stack, not just one half.
Where this fits in your learning
If the back end is new to you, start with our Spring Boot for beginners guide, especially your first REST API and Spring Security. For the Java fundamentals underneath, see Core Java for freshers.
To build full stack projects like this with a trainer in a classroom in BTM Layout or live online, see our Java full stack course in Bangalore or book a free demo class. For fees and batch dates, please contact a ScholarLogic counsellor on +91 78923 93639.
