首先,介紹一下軟件準備工作
1.vscode
2.maven
3.vue搭建:node.js+yarn+vite
一.后端搭建
打開vscode,建立一個springboot項目,參考鏈接:sping boot項目搭建
建立一個項目,目錄結構如下:
helloController.java
package example.example1;import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@CrossOrigin // 允許所有跨域請求(僅用于開發)
public class HelloController {@GetMapping("/hello")public String hello() {return "你好,Spring Boot! 當前時間: " + new java.util.Date();}
}
訪問瀏覽器:http://localhost:8080/hello
運行界面如下:
二.前端搭建
打開一個文件夾,建立一個vue項目,參考鏈接:vue項目創建
項目目錄結構如下:
public/index.html如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>極簡Vue+SpringBoot</title>
</head>
<body><div id="app"></div>
</body>
</html>
Components/App.vue如下:
<template><div><h1>Vite + Spring Boot 測試</h1><button @click="fetchData">獲取后端數據</button><div v-if="message">{{ message }}</div><div v-if="error" style="color: red">{{ error }}</div></div>
</template><script>
export default {data() {return {message: '',error: ''}},methods: {async fetchData() {try {const response = await fetch('/api/hello') // 注意 /api 前綴this.message = await response.text()this.error = ''} catch (err) {this.error = '請求失敗: ' + err.message}}}
}
</script>
main.js如下:
import './assets/main.css'import { createApp } from 'vue'
import App from './App.vue'createApp(App).mount('#app')
vite.config.js如下
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'export default defineConfig({plugins: [vue()],server: {proxy: {'/api': {target: 'http://localhost:8080', // 你的 Spring Boot 后端地址changeOrigin: true,rewrite: (path) => path.replace(/^\/api/, '') // 去掉 /api 前綴}}}
})
運行界面如下:
點擊獲取后臺數據:
這樣就完成了前后端分離啦。
注意:要先運行后端再運行前端。
關鍵步驟總結:
一.后端搭建
1.首先,搭建后端,在servlet里面設置@CrossOrigin
2.用@GetMapping()定義訪問映射
編寫@GetMapping("/hello")定義訪問的映射
二.前端搭建:
1.用fetch方法來獲取數據
fetch
?是瀏覽器內置的一個用于發送網絡請求(如 HTTP 請求)的函數。它可以用來向服務器獲取數據或提交數據,常用于前后端分離項目中前端與后端的通信。
const response = await fetch('/api/hello')
這行代碼的意思是:向?/api/hello
?這個接口發送一個 GET 請求,等待服務器返回響應,然后把響應結果賦值給?response
?變量。
2.其中,api接口是自己在vite.config.js中定義的
?proxy: {
? ? ? '/api': {
? ? ? ? target: 'http://localhost:8080', // 你的 Spring Boot 后端地址
? ? ? ? changeOrigin: true,
? ? ? ? ?rewrite: (path) => path.replace(/^\/api/, '') // 去掉 /api 前綴
? ? ? }
? ? }
這樣訪問也就是訪問了http://localhost:8080/hello
當然,你也可以選擇把接口直接定義為hello,這樣地址就不用重寫了,就可以寫成,
?proxy: {
? ? ? '/hello': {
? ? ? ? target: 'http://localhost:8080', // 你的 Spring Boot 后端地址
? ? ? ? changeOrigin: true
? ? ? }
? ? }
不過,這樣?const response = await fetch('/api/hello') 也要改成?const response = await fetch('/hello')?