How to Connect Simple Example Program React JS Spring Boot  (Step by Step Process)

How to Connect Simple Example Program React JS Spring Boot (Step by Step Process)

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.


Sandeep Prajapati

Student @ C-DAC Noida MCA'25

4 个月

Very informative

要查看或添加评论,请登录

Sridhar Raj P的更多文章

  • Custom Hook

    Custom Hook

    Custom Hooks are a powerful feature introduced in React 16.8 that allow developers to extract and reuse stateful logic…

  • useReducer() Hook in React JS – Example & Explanation

    useReducer() Hook in React JS – Example & Explanation

    Hook in React JS – Example & Explanation The hook is an alternative to for managing complex state logic in React…

  • useReducer() Hook in React JS – Example & Explanation

    useReducer() Hook in React JS – Example & Explanation

    Hook in React JS – Example & Explanation The hook is an alternative to for managing complex state logic in React…

  • Passing Data from Child to Parent Component in React JS using Hooks

    Passing Data from Child to Parent Component in React JS using Hooks

    Passing Data from Child to Parent Component in React JS using Hooks In React, data flows from parent to child via…

  • Lists and Keys in React JS

    Lists and Keys in React JS

    In React, we use lists to render multiple components dynamically, and keys help React identify which items have…

    1 条评论
  • Object State Management

    Object State Management

    Object State Management Managing object state with in React is common when handling complex data structures like user…

  • useState Example

    useState Example

    Here are examples of using the hook in React functional components. Each example demonstrates a different use case.

  • Examples of using the useState hook in React Functional Components

    Examples of using the useState hook in React Functional Components

    Examples of using the useState hook in React Functional Components 1. Counter Example - ? Basic counter with increment…

  • Array, Array of Objects Values using Functional Component

    Array, Array of Objects Values using Functional Component

    Example 1: Displaying an Array of Strings import React from react; const FruitsList = () = { const fruits = [Apple…

    1 条评论
  • Hooks

    Hooks

    What are Hooks in React JS? Hooks in React allow functional components to manage state and side effects, which were…

社区洞察

其他会员也浏览了