vue+SpringBoot前后端通信

一、前端环境

前端使用的所有插件及软件版本相关信息

  "dependencies": {
    "axios": "^1.7.5",
    "core-js": "^3.8.3",
    "vue": "^3.2.13",
    "vue-router": "^4.0.3",
    "vuex": "^4.0.0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-router": "~5.0.0",
    "@vue/cli-plugin-vuex": "~5.0.0",
    "@vue/cli-service": "~5.0.0"
  },
  "system": {
    "nodejs": "^16.20.2",
    "npm": "^8.19.4"
  }

1、创建前端项目

使用Web Storm创建vue项目
在这里插入图片描述

使用方向键选择第三个,所有需要的功能自行选择,选择完毕敲击回车
在这里插入图片描述

使用空格键在需要的功能前打上*号,选择完毕敲击回车

在这里插入图片描述

选择vue版本

在这里插入图片描述

根据自己的需求选择接下来的几个选项

在这里插入图片描述

完成后等待相关依赖下载完毕,项目创建成功,下图为项目创建成功目录

yarn.lock文件为全局安装yarn命令生成,可以根据自己需求自行安装

在这里插入图片描述

2、安装axios

# NPM
npm install axios
# Yarn
yarn add axios
# pnpm
pnpm install axios

3、在src目录下创建utils文件夹,并创建自己的工具类文件,此处创建的为dongxueUtils.js

//dongxueUtils.js

/**
 * GET请求参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}

4、在src目录下创建config文件夹,并创建axios.js文件

//axios.js

import axios from 'axios';
// 此处引入上面创建的工具类中的tansParams方法
import { tansParams } from "@/utils/dongxueUtils";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const myAxios = axios.create({
    timeout: 5000 // 请求超时时间
});

// request拦截器
myAxios.interceptors.request.use(config => {
        // get、delete请求映射params参数
        if (config.method === 'GET' || config.method === 'DELETE') {
            let url = config.url + '?' + tansParams(config.params);
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }
        // post、put请求参数处理
        if (config.method === 'POST' || config.method === 'PUT') {
            url: config.url;
            data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data;
        }
        // 更多配置...
        return config;
    },
    error => {
        // 请求错误处理
        console.error('Request error:', error);
        return Promise.reject(error);
    }
);

// response 拦截器
myAxios.interceptors.response.use(
    response => {
        const res = response.data;
        // 可以在这里根据返回的数据进行一些处理
        // 比如根据状态码具体处理
        return res;
    },
    error => {
        console.error('Response error:', error);
        return Promise.reject(error);
    }
);
export default myAxios;

5、在src目录下创建api文件夹,并创建temp.js文件对请求方法进行封装

//temp.js

import myAxios from "@/config/axios";

// 测试查询
export function tempTest(query) {
    return myAxios({
        url: '/api/test',
        method: 'get',
        params: query
    })
}

6、在vue.config.js文件中配置后端服务器信息

//vue.config.js

const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({
    transpileDependencies: true,
    // 开发服务器配置
    devServer: {
        // 自动打开浏览器
        open: true,
        // 用于配置开发服务器的代理,以解决开发过程中的跨域问题。
        proxy: {
            '/api': {
                // 目标服务器的地址。这里设置为你的后端 API 服务器地址。
                target: 'http://localhost:8080',
                // 设置为true表示允许跨域。它会将请求头中的Host和Origin字段设置为目标服务器的地址,使得目标服务器认为请求来自它自己的域名。
                changeOrigin: true,
                // 用于重写请求路径。例如,当请求路径为/api/some-endpoint时,通过pathRewrite将其重写为/some-endpoint,然后发送到目标服务器。
                pathRewrite: {
                    '^/api': ''
                }
            }
        }
    }
})

7、修改AboutView.vue文件测试是否成功

//AboutView.vue

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <button @click="myTest">跳转页面</button>
    <h1>前端获取到的数据 --- {{ tempData }}</h1>
  </div>
</template>

<script>
import {tempTest} from "@/api/temp";
import {ref} from "vue";

export default {
  setup() {
    let tempData = ref();

    function myTest() {
      tempTest().then((data) => {
            this.tempData = data;
            console.log(data)
            console.log("-----------------------")
            console.log("测试完成")
          }
      )
    }

    return {myTest, tempData};
  }
};
</script>

二、后端环境

1、创建后端项目

使用IntelliJ IDEA创建后端SpringBoot项目

在这里插入图片描述

选择需要的依赖

在这里插入图片描述

等待加载完成,项目创建成功,下图为项目创建成功目录

在这里插入图片描述

2、在公司域名包下创建controller文件及TestController类文件,修改配置文件后缀,删除无用文件夹及文件

在这里插入图片描述

3、修改application.yml配置文件及TestController类文件内容

在这里插入图片描述

//application.yml

server:
  port: 8080
//TestController.java

package com.dongxue.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author dongxue
 * @date 2024/8/30
 */
@RestController
@RequestMapping
public class TestController {

    @GetMapping("/test")
    public String test(){
        System.out.println("已接收到前端请求");
        return "后端接收到前端数据";
    }
}

三、测试

1、先启动后端项目

在这里插入图片描述

2、启动前端项目

在这里插入图片描述

3、切换至About页面

在这里插入图片描述

4、测试是否通信成功

在这里插入图片描述

  • 13
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值