This project demonstrates how to connect a React frontend with a Spring Boot backend. The React app sends an HTTP request to the Spring Boot API and displays the response in the browser. CORS configuration has been set up to allow the frontend to communicate with the backend.
- React app sends a GET request to the Spring Boot backend.
- Displays a response from the backend on the frontend.
- Handles CORS issues by configuring Spring Boot to allow requests from
http://localhost:3000
. - Graceful error handling in case of failed API requests.
Before running the project, ensure you have the following installed:
- Node.js: Download and install Node.js.
- Java 17 or later: Download and install Java.
- Maven: For building and running the Spring Boot project. Download Maven.
-
Clone or download the backend project from the repository.
-
Navigate to the
SpringReactConnect
folder. -
Ensure the backend dependencies are installed by running:
mvn clean install
-
Run the Spring Boot application:
mvn spring-boot:run
-
The backend will be available at
http://localhost:8080/api/hello
. Ensure the backend is up and running.
-
Navigate to the
react-frontend
folder (or create one usingcreate-react-app
if not done already). -
Install necessary dependencies:
npm install axios
-
Ensure the frontend is configured to request the backend API at
http://localhost:8080/api/hello
. -
Start the React app:
npm start
-
The React app will be available at
http://localhost:3000
.
- The Spring Boot backend is configured to handle CORS by allowing requests from
http://localhost:3000
. - The backend uses the
@CrossOrigin
annotation on the controller method and has a global CORS configuration.
If you encounter a CORS error, make sure that:
- The Spring Boot backend has the
@CrossOrigin
annotation or global CORS configuration. - The frontend React app is running on
http://localhost:3000
.
Ensure the Spring Boot server is running on http://localhost:8080
. You can check this by opening the browser and navigating to http://localhost:8080/api/hello
.
If you'd like to avoid manually specifying the backend URL in React, you can set up a proxy in package.json
:
"proxy": "http://localhost:8080"