How to Connect Simple Example Program React JS Spring Boot (Step by Step Process)
Sridhar Raj P
?? On a mission to teach 1 million students | Developer & Mentor | 5,500+ Students ?? | JavaScript | React JS | Redux | Python | Java | Springboot | MySQL | Self-Learner | Problem Solver
To connect a React JS frontend with a Spring Boot backend, we'll build a simple application that demonstrates the steps for integration. The example will involve a basic REST API in Spring Boot and a React frontend that communicates with it.
Overview
1. Spring Boot Backend:
- Create a Spring Boot project.
- Build a simple REST API that returns data.
2. React Frontend:
- Create a React app.
- Fetch data from the Spring Boot backend using fetch or axios.
Let's go step by step.
Step 1: Create a Spring Boot Backend
1. Set Up a Spring Boot Project
- You can create a Spring Boot project using [Spring Initializr](https://start.spring.io/).
- Select the following options:
- Project: Maven
- Language: Java
- Spring Boot Version: Latest stable version
- Dependencies: Spring Web
- Download the project, unzip it, and open it in your favorite IDE (e.g., IntelliJ, Eclipse, or VS Code).
2. Create a Simple REST Controller
- In the src/main/java/com/example/demo directory, create a new Java class named HelloController.java.
// src/main/java/com/example/demo/HelloController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello from Spring Boot!";
}
}
3. Run the Spring Boot Application
- The main application class (`DemoApplication.java`) should already be present in the src/main/java/com/example/demo directory.
- Run the application using the command:
./mvnw spring-boot:run
- The Spring Boot server will start on https://localhost:8080.
4. Test the API Endpoint
- Open a web browser and navigate to https://localhost:8080/api/hello.
- You should see the message: "Hello from Spring Boot!".
Step 2: Create a React Frontend
1. Set Up a React App
- If you don't have a React app set up yet, create one using: npx create-react-app react-frontend
- Navigate to the project directory: cd react-frontend
2. Install Axios (Optional)
- We will use axios to make HTTP requests to the Spring Boot API. You can also use the native fetch API.
- Install axios: npm install axios
3. Create a Component to Fetch Data
- Update the src/App.js file to fetch data from the Spring Boot backend.
// src/App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [message, setMessage] = useState('');
useEffect(() => {
// Fetch data from the Spring Boot backend
axios.get('https://localhost:8080/api/hello')
.then(response => {
setMessage(response.data);
})
.catch(error => {
console.error('There was an error fetching the data!', error);
});
}, []);
领英推荐
return (
<div className="App">
<header className="App-header">
<h1>React & Spring Boot Integration</h1>
<p>{message}</p>
</header>
</div>
);
}
export default App;
4. Run the React App
- Start the React development server: npm start
- Open your browser and navigate to https://localhost:3000.
- You should see a message that says: "Hello from Spring Boot!".
Step 3: Handle CORS Issues
If the React app and the Spring Boot backend are running on different ports (e.g., 3000 for React and 8080 for Spring Boot), you will run into a Cross-Origin Resource Sharing (CORS) issue.
1. Enable CORS in Spring Boot
- Update the HelloController class to allow CORS:
import org.springframework.web.bind.annotation.CrossOrigin;
@RestController
@RequestMapping("/api")
public class HelloController {
@CrossOrigin(origins = "https://localhost:3000")
@GetMapping("/hello")
public String sayHello() {
return "Hello from Spring Boot!";
}
}
Alternatively, you can enable CORS globally by creating a configuration class:
// src/main/java/com/example/demo/WebConfig.java
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://localhost:3000");
}
};
}
}
Restart the Spring Boot application for the changes to take effect.
Step 4: Verify the Integration
1. Make sure both the React and Spring Boot servers are running.
2. Navigate to https://localhost:3000 in your web browser.
3. The React app should successfully fetch and display the message from the Spring Boot backend.
Optional Step: Build and Deploy
1. Build the React App
- Run: npm run build
- This will create a build directory with the static files.
2. Serve the React Build with Spring Boot
- Move the contents of the build directory to the src/main/resources/static directory in the Spring Boot project.
- Now, when you run the Spring Boot application, it will serve the React app at https://localhost:8080.
Summary
You've now created a basic integration between a React frontend and a Spring Boot backend:
- Spring Boot Backend: Provides a simple REST API.
- React Frontend: Fetches and displays data from the backend.
- CORS Configuration: Enables cross-origin requests.
Student @ C-DAC Noida MCA'25
4 个月Very informative