0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【入門】Vue × Spring BootでToDoアプリを作ってみた!REST API連携の解説

Last updated at Posted at 2025-04-04

Vue × Spring BootでToDoアプリを作ってみた!REST API連携の解説

はじめに

Spring Boot と Vue 3 を使って ToDo アプリを作ってみたので、記録用にまとめておきます!

  • 初心者向け
  • REST API 連携
  • CORS問題の対処方法など、はまりやすいポイントを解説

システム構成

  • Frontend: Vue 3 + Vite + Axios
  • Backend: Spring Boot + Java 17 + Lombok + Spring Data JPA
  • DB: (今回は使用していないが抽象化)
  • Port: Vue = 5173, Spring Boot = 8000

Vue 側の設定

プロジェクト作成

npm create vite@latest vue-todo-app --template vue
cd vue-todo-app
npm install
npm install axios
npm run dev

初期表示

TodoList.vue
<script setup>
import axios from 'axios';
import { onMounted, ref } from 'vue';

const tasks = ref([]);

onMounted(async () => {
  const res = await axios.get('http://localhost:8000/api/todos');
  tasks.value = res.data;
});
</script>

<template>
  <div v-for="task in tasks" :key="task.id">
    <span>{{ task.context }}</span>
  </div>
</template>

☕ Spring Boot 側の設定

Spring Initializr で生成

  • Web
  • Lombok
  • Spring Data JPA
  • Validation

Controller

TodoController.java
@RestController
@CrossOrigin("http://localhost:5173")
@RequestMapping("/api/todos")
@RequiredArgsConstructor
public class TodoController {
    private final TodoService service;

    @GetMapping
    public List<Todo> getAllTodos() {
        return service.getAllTodos();
    }

    @PostMapping
    public Todo createTodo(@RequestBody Todo todo) {
        return service.createTodo(todo);
    }

    @PutMapping("/{id}")
    public Todo updateTodo(@PathVariable Integer id, @RequestBody Todo updateTodo) {
        return service.updateTodo(id, updateTodo);
    }

    @DeleteMapping("/{id}")
    public void deleteTodo(@PathVariable Integer id) {
        service.deleteTodo(id);
    }
}

⚠️ よくあるハマりポイント

問題 原因
404 エラー URLのポート間違い (51738000 の間違い)
CORS エラー Spring側に @CrossOrigin 設定がない

✅ まとめ

  • Vue と Spring Boot を組み合わせると、フロントエンドとバックエンドを分離して開発できる
  • axiosと REST API の連携は役立つ
  • CORS問題は最初に決着しておくとよい
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?