首页 > 编程语言 > 详细

SpringBoot + Vue3.x + vite2.x 前后端分离项目构建

时间:2021-03-16 22:20:58      阅读:170      评论:0      收藏:0      [点我收藏+]

1. 构建Springboot项目

  1. 构建Controller

    @ResponseBody
    @RequestMapping(path = "/helloWorld", method = RequestMethod.GET)
    public String helloWorld() {
        return "Hello World !";
    }
    
  2. 构建跨域配置

    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedHeaders("*")
                    .allowedMethods("*")
                    .maxAge(1800)
                    .allowedOrigins("http://localhost:3000");//前端服务器IP和端口号
        }
    }
    

2. 构建Vue项目

  1. 在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,
      },
    
  2. 构建页面

    <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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!