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

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>
    
posted @ 2021-03-16 20:58  有你何须仰望  阅读(696)  评论(0编辑  收藏  举报