0
0

Vue.js と Spring Boot を連携基本

Last updated at Posted at 2024-08-27

1. Spring Boot で REST API を構築する

まずはバックエンド側の Spring Boot で、簡単な REST API を作成します。このAPIは、ユーザーのリストを返すエンドポイントを提供します。

napkin-selection (13).png

Spring Boot の準備

Spring Initializr を使って、新しい Spring Boot プロジェクトを作成します。Web依存関係を追加しておきましょう。

コントローラーの作成
次に、UserController というコントローラーを作成し、ユーザー情報を返すエンドポイントを定義します。

@RestController
@RequestMapping("/api")
public class UserController {

    @GetMapping("/users")
    public List<User> getUsers() {
        // ユーザーリストを返す
        return List.of(new User(1, "Alice"), new User(2, "Bob"));
    }
}

/api/users にGETリクエストを送ると、以下のようなJSON形式のデータが返されます。

[
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" }
]

2. Vue.js プロジェクトを作成する

次に、Vue.js を使ってフロントエンドのプロジェクトを作成し、Spring Boot のAPIと通信します。

Vue CLI を使ったプロジェクト作成
まず、Vue CLI を使って新しいプロジェクトを作成します。

vue create my-project
cd my-project
npm install axios

Axios を使った API 呼び出し

App.vue や任意のコンポーネントで、Axios を使って Spring Boot のAPIを呼び出します。

<template>
  <div>
    <h1>User List</h1>
    <ul>
      <li v-for="user in users" :key="user.id">{{ user.name }}</li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: []
    };
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    async fetchUsers() {
      try {
        const response = await axios.get('http://localhost:8080/api/users');
        this.users = response.data;
      } catch (error) {
        console.error("There was an error fetching the users!", error);
      }
    }
  }
};
</script>

CORS(クロスオリジン)の設定

開発中に、Vue.js と Spring Boot が異なるポートで動作している場合、CORSの問題が発生することがあります。この問題を解決するために、Spring Boot 側で CORS を設定します。

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:8080") // Vue.jsの開発サーバーのURL
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0