Vue利用axios发送请求并代理请求

由于浏览器的同源策略 ,发送请求时常常遇到跨域问题 ,一种解决办法是让后端配置跨域,还有一种就是使用代理(与前端工程一起启动,同一个端口),因为代理不是通过浏览器发送的,所以不受同源策略的限制

服务器代码

用SpringBoot工程(端口为8082)简单写了一个Controller层,用于·接收前端发来的请求,并返回数据,前端请求

http://localhost:8082/students 时会返回学生列表数据 ,访问 http://localhost:8082/cars 时会返回汽车列表数据

java 复制代码
import com.example.pojo.Car;
import com.example.pojo.Student;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class TestController {

    private List<Student>studentList=List.of(
            Student.builder().id("001").name("张三").age(Short.valueOf("18")).build(),
            Student.builder().id("002").name("李四").age(Short.valueOf("19")).build(),
            Student.builder().id("003").name("王五").age(Short.valueOf("20")).build()
    );

    private List<Car>carList=List.of(
            Car.builder().id("001").name("奥迪").price(100000F).build(),
            Car.builder().id("002").name("玛莎拉蒂").price(500000F).build(),
            Car.builder().id("003").name("奔驰").price(300000F).build()
    );

    @GetMapping("/students")
    public List<Student>getStudentList(){
        return studentList;
    }

    @GetMapping("/cars")
    public List<Car>getCarList(){
        return carList;
    }

}

前端代码

通过配置代理进行请求的转发,实现跨域访问,在vue.config.js文件中配置如下代码

javascript 复制代码
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,

  //开启代理服务器
  devServer:{
    proxy: {
      '/api': {
        target: 'http://localhost:8082/', // 你想要代理到的地址
        pathRewrite: {
          '^/api': '/' // 重写路径,将 /api 替换为 /
        }
      }
    }
  }
})

通过axios发送请求,先在终端输入 npm i axios 引入axios的依赖包,然后通过一下代码发送请求

javascript 复制代码
axios.get("/api/students")
    .then(
    	//请求成功的回调函数
        response=>{
            this.studentList=response.data
         },
    	//请求失败的回调函数
        err=>{
            alert(err.message)
        }
    )
相关推荐
陈随易1 小时前
Postman 被曝自动往 Claude Code 和 Codex 装插件
前端·后端·程序员
Dream-Y.ocean4 小时前
鸿蒙PC平台宅匠 3D 室内设计适配实战:基于 Electron 壳方案的 Three.js 双渲染引擎与参数化户型编辑器开发
javascript·3d·harmonyos
Csvn4 小时前
性能监控
前端
Highcharts.js5 小时前
Highcharts Gantt使用符号的自定义数据标签开发甘特图示例
javascript·甘特图·highcharts·图表开发·实战代码·响应式图表
Csvn5 小时前
构建工具
前端
FRing035 小时前
vue2干货总结3(computed计算属性、watch监听器)
开发语言·前端·vue.js·vue2
Java小卷6 小时前
JuanForm vs FormCreate!Vue3 表单引擎联动配置 PK!
vue.js·低代码
kyriewen8 小时前
Skills 榜前 10 我全装了:只有 3 个能直接用
前端·javascript·程序员
IT_陈寒8 小时前
当Java的hashCode遇上Lombok,我的缓存被全清了
前端·人工智能·后端
工控丫丫8 小时前
帆软看板中经常使用的公式函数及经常搭的组合
前端·javascript·数据库