当前位置: 首页 > Web前端 > vue.js

Ajax

时间:2023-03-31 21:55:12 vue.js

1.1inVue使用代理服务器1.1.1方法一在vue.config.js中添加如下配置:devServer:{proxy:"http://localhost:5000"}说明:优点:配置简单,容易request资源可以直接发送给前端(8080)。缺点:不能配置多个代理,无法灵活控制请求是否走代理。工作方式:如果代理如上配置,当请求前端不存在的资源时,会把请求转发给服务端(先匹配前端资源)1.1.2方法二写vue.config.js来配置具体的代理规则:module.exports={devServer:{proxy:{'/api1':{//匹配所有以'/api1'开头的请求路径target:'http://localhost:5000',//代理目标的基本路径changeOrigin:true,pathRewrite:{'^/api1':''}},'/api2':{//匹配所有以'/api2'开头的请求路径target:'http://localhost:5001',//代理目标基础pathchangeOrigin:true,pathRewrite:{'^/api2':''}}}}}/*changeOrigin设置为true,服务器收到的请求头中的host为:localhost:5000当changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080changeOrigin默认值为true*/说明:优点:可以配置多个代理,可以灵活控制请求是否走代理。缺点:配置略繁琐,请求资源时必须加前缀。1.2Vue项目常用的两个Ajax库1.2.1Axios说明:通用Ajax请求库,官方推荐,广泛使用安装:npminstallaxios使用步骤:importimportaxiosfrom"axios";使用axios.get("http://localhost:8080/api/students").then((response)=>{console.log("requestsucceeded",response.data);},(error)=>{console.log("请求失败",error.message);});1.2.2vue-resourceVue插件库,Vue1.x使用广泛,官方不再维护