【Vue】Vue+SpringBoot Axios网络请求

该文介绍了如何在Vue项目中通过main.js配置axios请求后端API,设置默认基础URL为本地8088端口。在组件中利用生命周期函数created进行网络请求,获取后端/user/findAll接口的数据。后端使用SpringBoot,通过application.properties设置不同端口避免冲突,并用@RestController和@CrossOrigin注解处理控制器和跨域问题。
摘要由CSDN通过智能技术生成

前端Vue

在main.js文件中配置后端端口号

import axios from 'axios'

//配置请求根地址
axios.default.baseURL = "http://localhost:8088"

//自定义属性$http
//将axios作为全局的自定义属性,每个组件可在内部直接访问
//axios不需额外在每个组件的script中导入axios
Vue.protptype.$http = axios;

在组件的created生命周期函数中进行网络请求

<template>
  <div>
    <el-table :data="tableData">
      <el-table-colomn lable="ID" slot-scope="{row}">
        {{row.id}}
      </el-table-colomn>
      <el-table-colomn lable="name" slot-scope="{row}">
        {{row.name}}
      </el-table-colomn>
    </el-table>
  </div>            
</template>
<script>
export default{
  data(){
    return {
      tableData: []
    }
  },
  created:function(){
    //对应后端相应地址
    //在main.js文件中定义过$http,因此this.$http=axios,axios不需额外导入
    //get自动连接main.js文件中的baseURL
    this.$http.get("/user/findAll").then((response) => {
      //根据后端返回的数据
      //从后端拿到的数据赋值给tableData
      this.tableData = response.data
    }
  }
}
</script>

后端SpringBoot

在application.properties中修改端口号,避免与前端端口号冲突

server.port = 8088

controller控制类

@RestController
@RequestMapping("/user")
//解决跨域问题
@CrossOrigin
public class UserController{
    
    @Autowired
    UserMapper userMapper;

    @GetMapping("/findAll")
    public List<User> find() {
        return userMapper.selectAllUser();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秃头的少女

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值