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のポート間違い (5173 と 8000 の間違い) |
CORS エラー | Spring側に @CrossOrigin 設定がない |
✅ まとめ
- Vue と Spring Boot を組み合わせると、フロントエンドとバックエンドを分離して開発できる
- axiosと REST API の連携は役立つ
- CORS問題は最初に決着しておくとよい