When building modern full-stack web applications, separating the frontend UI from the backend business logic is standard practice. A common challenge developers encounter when connecting a React application to a Spring Boot backend is handling Cross-Origin Resource Sharing (CORS) and state synchronization.
In this tutorial, you will learn how to build a RESTful API in Spring Boot, expose an endpoint, and fetch data from a React frontend.
Prerequisites
Before starting, ensure you have the following installed on your machine:
-
Node.js (v18+) &
npm - Java Development Kit (JDK 17+)
- Maven or Gradle
Step 1: Setting Up the Spring Boot Backend
First, configure a Spring Boot controller to serve a JSON endpoint and handle CORS requests.
Create the Controller (WeatherController.java)
package com.example.demo.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:5173") // Enables React frontend origin
public class WeatherController {
@GetMapping("/status")
public Map<String, String> getStatus() {
Map<String, String> response = new HashMap<>();
response.put("status", "Online");
response.put("message", "Backend successfully connected to React!");
return response;
}
}
Key Note: The
@CrossOriginannotation prevents CORS errors when making fetch calls from your local React development server.
Step 2: Setting Up the React Frontend
Now, create a React component using standard hooks (useState and useEffect) to call the Spring Boot API.
Create the Fetch Component (ApiStatus.jsx)
import { useState, useEffect } from 'react';
export default function ApiStatus() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('http://localhost:8080/api/status')
.then((res) => {
if (!res.ok) throw new Error('Failed to reach backend');
return res.json();
})
.then((data) => {
setData(data);
setLoading(false);
})
.catch((err) => {
setError(err.message);
setLoading(false);
});
}, []);
if (loading) return <p>Connecting to Spring Boot backend...</p>;
if (error) return <p style={{ color: 'red' }}>Error: {error}</p>;
return (
<div style={{ padding: '20px', border: '1px solid #ccc' }}>
<h3>Backend Connection Status</h3>
<p><strong>Status:</strong> {data.status}</p>
<p><strong>Message:</strong> {data.message}</p>
</div>
);
}
Step 3: Verifying the Connection
- Run your Spring Boot application using
./mvnw spring-boot:run(runs on port 8080 by default). - Start your React dev server using
npm run dev(runs on port 5173). - Open your browser to
http://localhost:5173. You should see the message: "Backend successfully connected to React!"
Conclusion
Connecting React with Spring Boot requires configuring CORS policy annotations on the backend and managing API loading/error states cleanly in the React frontend.
Top comments (0)