最简单的springboot+axios实例,并解决跨域问题

一、创建最简单的springboot项目

这里作者只创建了一个UserController

二、创建最简单的vue实例

1、这里的vue要先安装axios依赖

npm install axios

2、创建按钮和对应的函数,并且导入axios

3、开始使用axios发送请求

这里作者根据后端发送姓名和密码,axios第一个参数是url,第二个是传递对象

<template>
  <div>
    <!-- 发送请求测试按钮 -->
    <button @click="handlerSend">发送请求</button>
  </div>
</template>
<script setup>
//导入axios
import axios from 'axios';

//处理按钮的点击事件
const handlerSend = () => {
  console.log('发送请求');
  axios.post('/api/user/login',{
    username:'admin',
    password:'123456'
  }).then(res => {
    console.log(res);
  }).catch(err => {
    console.log(err);
  })
}
</script>

然后处理获得的结果

const handlerSend = () => {
  aixos.post('/api/user/login',{
    username:'admin',
    password:'123456'
  }).then(res => {
    console.log(res);
  }).catch(err => {
    console.log(err);
  })
}

4、解决跨域问题

在config.js文件中添加代理

 server:{
    proxy:{
      '/api':{
        target:'http://localhost:8080',
        changeOrigin:true,
        rewrite:path=>path.replace(/^\/api/,'')
      }
    }
    }
  }

三、运行效果

我们还可以把后端的数据显示在前端

四、源代码

源代码在gitee上https://gitee.com/zyGitee983/learning-notes.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值