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

vue 脚手架配置代理

一、脚手架配置代理(devServer.proxy)

(一)、方法一

        在vue.config.js中添加如下配置:

        devServer:{

                proxy:"http://localhost:5000"

        }

         说明:

                1.有点:配置简单,请求资源时直接发给前端(8080)即可。

                2.缺点:不能配置多个代理,不能灵活的控制请求是否走代理。

                3.工作方式:若按照上述配置代理,当前请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源)。

 /*    vue.config.js    */
.................
module.exports = defineConfig({.................devServer:{proxy:'http://localhost:5000'}
})
/*    App.vue    */
<template><div><button @click="getStudents">获取学生信息</button></div>
</template><script>import axios from 'axios'export default {name:'App',methods:{getStudents(){axios.get('http://localhost:8080/students').then(response=>{console.log('请求成功了!',response.data)},error=>{console.log('请求失败了!',error.message)})},},}
</script>

        当public目录中有students时,会优先向前端请求资源。

(二)、方法二

        编写vue.config.js配置具体代理规则:

module.exports = {
    devServer: {
      proxy: {
      '/api1': {// 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api1': ''} //将路径中的'/api1'替换为''空字串
      },
      '/api2': {// 匹配所有以 '/api2'开头的请求路径
        target: 'http://localhost:5001',// 代理目标的基础路径

        pathRewrite: {'^/api2': ''} //将路径中的'/api2'替换为''空字串
        changeOrigin: true,

        // ws:true //用于支持websocket
      }
    }
  }
}
/*
   changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
   changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
   changeOrigin默认值为true
*/

        说明:

                1.优点:可以配置多个代理,且可以灵活的控制请求是否走代理。

                2.缺点:配置略微繁琐,请求资源时必须加前缀。

/*    vue.config.js    */
................
module.exports = defineConfig({................devServer:{proxy:{'/api':{target:'http://localhost:5000',pathRewrite:{'^/api':''}// ws:true,// changeOrigin:true,},'/demo':{target:'http://localhost:5001',pathRewrite:{'^/demo':''}// ws:true,// changeOrigin:true,},}}
})
/*    App.vue    */
<template><div><button @click="getStudents">获取学生信息</button><button @click="getCars">获取汽车信息</button></div>
</template><script>import axios from 'axios'export default {name:'App',methods:{getStudents(){axios.get('http://localhost:8080/api/students').then(response=>{console.log('请求成功了!',response.data)},error=>{console.log('请求失败了!',error.message)})},getCars(){axios.get('http://localhost:8080/demo/cars').then(response=>{console.log('请求成功了!',response.data)},error=>{console.log('请求失败了!',error.message)})}},}
</script>

二、Github搜索案例_axios应用

        以下是Github搜索案例的代码。

/*    App.vue    */
<template><div class="container"><Search/><List/></div>
</template><script>import Search from './Components/Search.vue'import List from './Components/List.vue'export default {name:'App',components:{Search,List}}
</script>
/*    Search.vue    */
<template><section class="jumbotron"><h3 class="jumbotron-heading">Search Github Users</h3><div><input type="text" placeholder="enter the name you search" v-model="userName"  @keydown.enter="loseFocus" @blur="getUsers" ref="search"/>&nbsp;<button @click="getUsers">Search</button></div></section>
</template><script>import axios from 'axios'export default {name:'Search',data() {return {userName:''}},methods:{getUsers(){if(this.userName.trim()){this.$bus.$emit('getUsers',{isHello:false,isLoading:true,msg:'',users:[]})axios.get(`https://api.github.com/search/users?q=${this.userName}`).then(Response=>{this.$bus.$emit('getUsers',{isLoading:false,msg:'',users:Response.data.items})},Error=>{this.$bus.$emit('getUsers',{isLoading:false,msg:Error.message,users:[]})})}},loseFocus(){this.$refs.search.blur()}}}
</script>
/*    List.vue    */
<template><div class="row"><!-- 展示列表数据 --><div class="card" v-for="user in info.users":key="user.id"v-show="info.users.length"><a :href="user.html_url" target="_blank"><img :src="user.avatar_url" style='width: 100px'/></a><p class="card-text">{{ user.login }}</p></div><!-- 展示欢迎 --><h2 v-show="info.isHello">Welcome to Github</h2><!-- 展示加载 --><h2 v-show="info.isLoading">Loading.......</h2><!-- 展示错误信息 --><h2 v-show="info.msg">{{ info.msg }}</h2></div>
</template><script>export default {name:'List',data() {return {info:{isHello:true,isLoading:false,msg:'',users:[]}}},mounted(){this.$bus.$on('getUsers',(obj)=>{this.info = {...this.info,...obj}})}};
</script><style scoped>
.album {min-height: 50rem; padding-top: 3rem;padding-bottom: 3rem;background-color: #f7f7f7;
}.card {float: left;width: 33.333%;padding: 0.75rem;margin-bottom: 2rem;border: 1px solid #efefef;text-align: center;
}.card > img {margin-bottom: 0.75rem;border-radius: 100px;
}.card-text {font-size: 85%;
}h2{padding: 1.5rem;
}
</style>

三、Github搜索案例_vue-resource应用

        vue-resource是 Vue.js 的一个插件,用于通过 XMLHttpRequest 或 JSONP 发起 HTTP 请求并处理响应。

        其使用方法与axios类似,用法如下:

                1.在main.js中引入并使用插件

        import VueResource from "vue-resource";

        ........................

        Vue.use(VueResource)

        .........................

                 2.vue-resource会在vm上挂载一个$http,使用时引用该变量即可,其余用法与axios基本相同:

        ..................................................

        methods:{

            getUsers(){

                if(this.userName.trim()){

                    this.$bus.$emit('getUsers',{isHello:false,isLoading:true,msg:'',users:[]})

                    this.$http.get(`https://api.github.com/search/users?q=${this.userName}`).then(

                        Response=>{

                            this.$bus.$emit('getUsers',{isLoading:false,msg:'',users:Response.data.items})

                        },

                        Error=>{

                            this.$bus.$emit('getUsers',{isLoading:false,msg:Error.message,users:[]})

                        }

                    )

                }

            },

            ..................................................

        }

http://www.xdnf.cn/news/1188721.html

相关文章:

  • RS485转Profinet网关配置指南:高效启动JRT激光测距传感器测量模式
  • 深入解析三大Web安全威胁:文件上传漏洞、SQL注入漏洞与WebShell
  • Qt 线程池设计与实现
  • HTML 音频/视频
  • 从一个“诡异“的C++程序理解状态机、防抖与系统交互
  • 2025年02月11日 Go生态洞察:Go 1.24 发布亮点全面剖析
  • 二叉搜索树(Binary Search Tree)详解与java实现
  • 【RK3568 PWM 子系统(SG90)驱动开发详解】
  • 记录和分享抓取的数字货币和大A时序数据
  • k8s:将打包好的 Kubernetes 集群镜像推送到Harbor私有镜像仓库
  • 容器化成本优化:K8s资源请求与限制的黄金法则——从资源画像分析到25%成本削减的实战指南
  • python面向对象编程详解
  • k8s之控制器详解
  • Go语言unsafe包深度解析
  • Go 多模块仓库标签管理教程
  • 嵌入式硬件篇---zigbee无线串口通信问题解决方法
  • Android 修改系统时间源码阅读
  • Linux的生态与软件安装
  • 主要分布在腹侧海马体(vHPC)CA1区域(vCA1)的混合调谐细胞(mixed-tuning cells)对NLP中的深层语义分析的积极影响和启示
  • 车载诊断刷写 --- Flash关于擦除和写入大小
  • 【MySQL】深入浅出事务:保证数据一致性的核心武器
  • 深度解析 noisereduce:开源音频降噪库实践
  • 【影刀RPA_初级课程_我的第一个机器人】
  • LeetCode|Day26|191. 位 1 的个数|Python刷题笔记
  • 像素、视野、光源,都有哪些因素影响测量精度?
  • DSP在CCS中实现双核在线仿真调试及下载的方法(以TMS320F28x为例)
  • 【Redis】 Redis 基础命令和原理
  • 详解力扣高频SQL50题之1193. 每月交易 I【简单】
  • MySQL操作进阶
  • 1. 多线程开发