构建Controller
@ResponseBody
@RequestMapping(path = "/helloWorld", method = RequestMethod.GET)
public String helloWorld() {
return "Hello World !";
}
构建跨域配置
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("*")
.maxAge(1800)
.allowedOrigins("http://localhost:3000");//前端服务器IP和端口号
}
}
在vite.config.ts配置跨域代理(只能在开发环境使用)
server: {
host: ‘localhost‘,//前端服务器IP
port: 3000,//前端服务器端口号
https: false,
open: false,
proxy: {
‘/api‘: {
target: ‘http://localhost:8080‘,//后端服务器端口号
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ‘‘),
},
},
cors: true,
},
构建页面
<template>
<button @click="fun1">点击</button>
<div>
{{ s }}
</div>
</template>
<script lang="ts">
import { defineComponent } from ‘vue‘
import axios from ‘axios‘
export default defineComponent({
name: ‘Hello‘,
data() {
return {
s: ‘hello‘,
}
},
methods: {
fun1: function () {
axios
.get(‘api/helloWorld‘)
.then((response) => {
this.s = response.data
})
.catch((error) => {
console.log(error)
})
},
},
})
</script>
SpringBoot + Vue3.x + vite2.x 前后端分离项目构建
原文:https://www.cnblogs.com/gjycn/p/14545837.html