当前位置: 首页 > article >正文

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

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

服务器代码

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

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

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文件中配置如下代码

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的依赖包,然后通过一下代码发送请求

axios.get("/api/students")
    .then(
    	//请求成功的回调函数
        response=>{
            this.studentList=response.data
         },
    	//请求失败的回调函数
        err=>{
            alert(err.message)
        }
    )


http://www.kler.cn/news/358967.html

相关文章:

  • 国产服务器KyLinV10操作系统部署harbor仓库时报错:open /etc/registry/passwd: permission denied
  • 计算机视觉——人像的分割与无缝融合
  • ORACLE 19C安装 RAC报错
  • RPC通讯基础原理
  • 计算机毕业设计Python动漫视频分析可视化 动漫影视可视化 动漫情感分析 动漫爬虫 机器学习 深度学习 Tensorflow PyTorch LSTM模型
  • 每天一个数据分析题(五百零八)- 机器学习模型
  • PPT自动化:Python如何修改PPT文字和样式!
  • 基于Multisim的乒乓球游戏机设计与仿真
  • 【网络安全】缓存欺骗问题之查看个人资料接口
  • Vue.js 组件开发基本步骤
  • 好用的软件
  • C# 委托/事件
  • 架构设计笔记-17-通信系统架构设计理论及实践
  • 什么是“河西走廊”?
  • 基于Java+Springboot+Vue开发的鲜牛奶订购管理系统
  • docker如何建立本地私有仓库,并将docker镜像推到私有仓库
  • 置分辨率设置多显示器的时候提示, 某些设置由系统管理员进行管理
  • Spring Cloud --- Gateway自定义条件过滤器
  • unity的一个bug
  • 三元组表矩阵运算