Seamlessly Connecting Vue.js with Spring Boot : A Step-by-Step Guide

Seamlessly Connecting Vue.js  with Spring Boot : A Step-by-Step Guide

Integrating a powerful frontend framework like Vue.js with a robust backend framework like Spring Boot is a popular choice in modern web development. Vue.js handles the dynamic and interactive user interface, while Spring Boot provides a scalable backend to process business logic and handle database interactions. In this blog, we’ll connect a Vue.js frontend to a Spring Boot backend.

Step 1: Setting Up the Vue.js Frontend

Initialize a Vue.js Project

Start by creating a Vue.js project using Vue CLI:

npm install -g @vue/cli
vue create frontend
cd frontend
npm run serve

The development server will start, and you can see your Vue.js app running at http://localhost:8080

Install Axios for API Calls

To connect with the backend, install Axios for making HTTP requests

npm install axios

Structure Your Components

Create a services directory in your Vue project to organize your API logic. For example:

src/services/apiService.js

This will hold functions to interact with your Spring Boot backend.


Step 2: Setting Up the Spring Boot Backend

Create a Spring Boot Project

Use the Spring Initializr to generate a Spring Boot project with the below dependencies:

  1. Spring Web
  2. Spring Data JPA (if needed for database interaction)
  3. MySQL/PostgreSQL Driver (or H2 for in-memory databases)

Example Maven setup in pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

Write a Simple REST Controller

Create a REST controller to handle API requests. For example:

@RestController
@RequestMapping("/api")
public class ApiController {
    @GetMapping("/messageInfo")
    public ResponseEntity<String> sampleMessage() {
        return ResponseEntity.ok("Hello, welcome all");
    }
}

Run the Application

Start your Spring Boot application by running the Application.java class. The backend will be available at http://localhost:8081 (or another port if configured).


Step 3: Connect Vue.js to Spring Boot

Enable CORS in Spring Boot =>

To allow Vue.js to access the backend APIs, enable Cross-Origin Resource Sharing (CORS):

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
    }
}

Make API Calls from Vue.js

Use Axios to fetch data from the Spring Boot backend

src/services/apiService.js

import axios from 'axios';

const API_BASE_URL = 'http://localhost:8081/api';
export const sampleMessage = async () => {
    const responseData = await axios.get(`${API_BASE_URL}/messageInfo`);
    return responseData.data;
};

Update your Vue component to display the fetched data:

<template>
  <div>
    <h1>{{ messageInfo }}</h1>
  </div>
</template>

<script>
import { sampleMessage } from '@/services/apiService';

export default {
    data() {
        return {
            messageInfo: '',
        };
    },
    async created() {
    try {
      this.messageInfo = await sampleMessage();
    } catch (error) {
      console.error('Error fetching message:', error);
    }
  },
};
</script>

Step 4: Run and Test the Integration

Start both the frontend and backend servers:

# To Start Vue.js

npm run serve

# To Start Spring Boot

mvn spring-boot:run

Access the Vue.js application at http://localhost:8080. If everything is set up correctly, the frontend should display the message fetched from the backend API.


Step 5: Deployment

Bundle Vue.js for Production

Run the Vue.js build command to generate production-ready files:

npm run build

Copy the generated dist folder into your Spring Boot application's src/main/resources/static directory.

Serve Frontend with Spring Boot

Spring Boot will now serve the Vue.js files alongside the backend. Finally, test the above application by running the backend and you can access our application at http://localhost:8081.


Common Challenges and Solutions

CORS Issues:

Always configure CORS properly in the backend to prevent errors.

Port Conflicts:

Ensure the Vue.js and Spring Boot servers run on different ports during development.

API Path Issues:

Verify that the API paths match between the frontend and backend.


Conclusion

By following these steps, you’ve successfully integrated Vue.js with Spring Boot. This combination provides a clean separation between frontend and backend development while enabling seamless communication through REST APIs. As you scale your application, you can extend this setup with authentication, database integration, and other features.