数据请求库——axios 在实际项目开发中,前端页面所需要的数据往往需要从服务器端 获取,这必然涉及与服务器的通信,Vue推荐使用axios来完成Ajax请 求。本章将学习这个流行的网络请求库axios,它是对Ajax的封装。因 为其功能单一,只是发送网络请求,所以容量很小。axios也可以和其 他框架结合使用。下面就来看一下Vue如何使用axios请求数据。 1 什么是axios 在实际开发中,或多或少都会进行网络数据的交互,一般都是使 用工具来完成任务。现在比较流行的就是axios库。axios是一个基于 promise的HTTP库,可以用在浏览器和Node.js中。 axios具有以下特性: (1)从浏览器中创建XMLHttpRequests。 (2)从Node.js创建HTTP请求。 (3)支持Promise API。 (4)拦截请求和响应。 (5)转换请求数据和响应数据。 (6)取消请求。 (7)自动转换JSON数据。 (8)客户端支持防御XSRF。 2 安装axios 安装axios的方法有以下几种。 1.使用CDN方式 使用CDN方式安装,代码如下: <script src="https://unpkg.com/axios/dist/axios.min.js"></script> 2.使用NPM方式 在Vue脚手架中使用axios时,可以使用NPM安装方式,执行下面命 令安装axios: npm install axios--save 或者使用yarn安装,命令如下: npm add axios --save 安装完成后,在main.js文件中导入axios,并绑定到Vue的原型链 上。代码如下: //引入axios import axios from'axios //绑定到 Vue 的原型链上 Vue.prototype.$axios=axios; 这样配置完成后,就可以在组件中通过this.$axios来调用axios 的方法以发送请求。 3 基本用法 本节将讲解axios库的基本使用方法:JSON数据的请求、跨域请求 和并发请求。 3.1 axios的get请求和post请求 axios有get请求和post请求两种方式。 在Vue脚手架中执行get请求,格式如下: this.$axios.get('/url?key=value&id=l') .then(function(response){ //成功时调用 console.log(response) }) .catch(function(response){ //错误时调用 console.log(response) }) get请求接受一个URL地址,也就是请求的接口;then方法在请求 响应完成时触发,其中形参代表响应的内容;catch方法在请求失败的 时候触发,其中形参代表错误的信息。如果要发送数据,以查询字符 串的形式附加在URL后面,以“?”分隔,数据以key=value的形式组 织,不同数据之间以“&”分隔。 如果不喜欢URL后附加查询参数的方式,可以给get请求传递一个 配置对象作为参数,在配置对象中使用params来指定要发送的数据。 代码如下: this.$axios.get('/url',{ params :{ key:value, id:1 } }) .then(function(response){ console.log(response); }) .catch(function(error){ console.log(error); }); post请求和get请求基本一致,不同的是数据以对象的形式作为 post请求的第二个参数,对象中的属性就是要发送的数据。代码如 下: this.$axios.post('/user', username:"jack", password:"123456" }) .then(function(response){ //成功时调用 console.log(response) }) .catch(function(response){ //错误时调用 console.log(response) }) 接收到响应的数据后,需要对响应的信息进行处理。例如,设置 用于组件渲染或更新所需要的数据。回调函数中的response是一个对 象,它的属性是data和status,data用于获取响应的数据,status是 HTTP状态码。response对象的完整属性说明如下所示: { //config是为请求提供的配置信息 config:{}, //data是服务器发回的响应数据 data:{}, //headers是服务器响应的消息报头 headers:{}, //request是生成响应的请求 requset:{}, //status是服务器响应的HTTP状态码 status:200, //statusText是服务器响应的HTTP状态描述 statusText:'ok', } 成功响应后,获取数据的一般处理形式如下: this.$axios.get('http://localhost:8080/data/user.json') .then(function(response){ //user属性在Vue实例的data选项中定义 this.user=response.data; }) .catch(function(error){ console.log(error); }) 如果出现错误,则会调用catch方法中的回调,并向该回调函数传 递一个错误对象。错误处理一般形式如下: this.$axios.get('http://localhost:8080/data/user.json') .catch(function(error){ if(error.response){ //请求已发送并接收到服务器响应,但响应的状态码不是200 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); }else if(error.response){ //请求已发送,但未接收到响应 console.log(error.request); }else{ console.log("Error",error.message); } console.log(error.config); }) 3.2 请求JSON数据 已经了解了get和post请求,下面就来看一个使用axios请求JSON 数据的示例。 首先使用Vue脚手架创建一个项目,这里命名为axiosdemo,配置 选项默认即可。创建完成之后“cd”到项目,然后安装axios: npm install axios --save 安装完成之后,在main.js文件中配置axios,具体请参考2节 “安装axios”。 完成以上步骤,在目录中的public文件夹下创建一个data文件 夹,在改文件夹中创建一个JSON文件user.json。user.json内容如 下: [ { "name":"小明", "pass" :"123456" }, { "name","小红", "pass":"456789" } ] 提示 JSON文件必须放在public文件夹下面,若放在其他位置,则会请求 不到数据。 然后在HelloWorld.vue文件中使用get请求JSON数据,其中 http://localhost:8080是运行axiosdemo项目时给出的地址, data/user.json指public文件夹下的data/user.json。具体代码如 下: <template> <div class="hello"></div> </template> <script> export default{ name:"HelloWorld', created(){ this.$axios.get('http://localhost:8080/data/user.json') .then(function(response){ console.log(response); }) .catch(function(error){ console.log(error); }) } } </script> 在浏览器中输入http://localhost:8080运行项目,打开控制台, 可以发现控制台中已经打印了user.json文件中的内容,如图1所 示。 3.3 跨域请求数据 在上一节的示例中,使用axios请求同域下面的JSON数据,而实际 情况往往都是跨域请求数据。在Vue CLI中要想实现跨域请求,需要配 置一些内容。首先在axiosdemo项目目录中创建一个vue.config.js文 件,该文件是Vue脚手架项目的配置文件,在这个文件中设置反向代 理: module.exports ={ devServer:{ proxy:{ //api是后端数据接口的路径 "/api':{ //后端数据接口的地址 target: 'https://yiketianqi.com/api?version=v9&appid=24782869&appsecret=Vfo8Bk9S', changeOrigin:true,//允许跨域 pathRewrite:{ '^/api':''//调用时用api替代根路径 } } } }, lintOnSave:false//关闭eslint校验 } 其中target属性中的路径,是一个免费的天气预报API接口,接下 来我们就使用这个接口来实现跨域访问。首先访问 http://www.tianqiapi.com/index,打开“API文档”,注册自己的开 发账号,然后进入个人中心,选择“专业七日天气”,如图2所 示。 图2 专业七日天气 进入专业七日天气的接口界面,下面会给出一个请求的路径,这 个路径就是我们跨域请求的地址。完成上面的配置后在axiosdemo项目 的HelloWorld.vue组件中实现跨域请求: <template> <div class="hello"> {{city} } </div> </template> <script> export default{ name:'HelloWorld', data(){ return{ city:"" } }, created(){ //保存vue实例,因为在axios中,this指向的就不是vue实例了,而是axios var that=this; this.$axios.get('/api') then(function(response){ that.city =response.data.city console.log(response); }) .catch(function(error){ console.log(error); }) } } </script> 在浏览器中运行axiosdemo项目,在控制台中可以看到跨域请求的 数据,页面中也同时会显示请求的城市,如图3所示。 图3 跨域请求数据 3.4 并发请求 很多时候,可能需要同时调用多个后台接口,可以利用axios库提 供的并发请求助手函数来实现这个功能: axios.all(iterable) axios.spread(callback) 下面结合前面两小节的示例,修改HelloWorld组件的内容,实现 同时请求JSON数据和跨域请求数据。 <template> <div class="hello"></div> </template> <script> export default{ name:'HelloWorld', //定义请求方法 get1:function(){ return this.$axios.get('http://localhost:8080/data/user.json'); }, get2:function(){ return this.$axios.get('/api'); } }, created(){ var that=this; this.$axios.all([that.get1(),that.get2()]) .then(this.$axios.spread(function(get1,get2){ //两个请求现在都执行完成 //get1是that.get1()方法请求的响应结果 //get2是that.get2()方法请求的响应结果 console.log(get1); console.log(get2); })) }}; </script> 在浏览器中运行项目,可以看到打印了两条数据,如图4所 示。 4使用axios创建请求 可以通过向axios传递相关配置来创建请求。 get请求和post请求的调用形式如下: //发送get请求 this.$axios({ method:'get', url:/user/12345', }); //发送get请求 this.$axios({ method:"post', url:/user/12345', data:{ firstName:Fred', lastName :'Flintstone' } }); 例如使用get请求天气预报接口,修改HelloWorld组件,代码如 下: //发送get请求 this.$axios({ method:'get', url:'/api', }).then(function(response){ console.log(response) }); 在浏览器中运行axiosdemo项目,结果如图5所示。 为方便起见,axios库为所有支持的请求方法提供了别名。代码如 下: axios.request(config) axios.get(url[,config]) axios.delete(url[,config]) axios.head(url[,config]) axios.post(urll,datal,config]]) axios.put(url[,data[,config]]) axios.patch(url[,datal,config]]) 在使用别名方法时,url、method、data这些属性都不必在配置中 指定。 5 请求配置 axios库为请求提供了配置对象,在该对象中可以设置很多选项, 常用的是url、method、headers和params。其中只有url是必需的,如 果没有指定method,则请求将默认使用get方法。配置对象完整内容如 下: { //'url'是用于请求的服务器URL url:'/user', //'method'是创建请求时使用的方法 method:'get',//默认是 get //'baseURL'将自动加在'url'前面,除非'url'是一个绝对URL //它可以通过设置一个'baseURL'便于为axios实例的方法传递相对URL baseURL:"https://some-domain.com/api/', //'transformRequest'允许在向服务器发送前,修改请求数据 //只能用在'PUT','POST:和'PATCH'这几个请求方法 //后面数组中的函数必须返回一个字符串,或ArrayBuffer,或stream transformRequest:[function(data){ //对data 进行任意转换处理 } return data; }], //'transformResponse'在传递给then/catch前,允许修改响应数据 transformResponse:[function(data){ //对data 进行意转换处理 return data; }], //'headers'是即将被发送的自定义请求头,这里使用Ajax请求 headers:{'X-Requested-With':'XMLHttpRequest'}, //'params'是即将与请求一起发送的UR参数 //必须是一个无格式对象(plain object)或URSearchParams 对象 params:{ ID:12345 }, //'paramsSerializer'是一个负责'params'列化的数 //(e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer:function(params){ return Qs.stringify(params,{arrayFormat:brackets'}) }, //'data'是作为请求主体被发送的数据 //只适用于这些请求方法'PUT','POST'和PATCH' //在没有设置'transformequest'时,必须是以下类型之一: //-string,plain object,ArrayBuffer,ArrayBufferView,URLSearchParams //-浏览器专属:FormData,File,Blob //-Node 专属:Stream data:{ firstName:"Fred' }, //'timeout'指定请求超时的毫秒数(0表示无超时时间) //如果请求超过'timeout'的时间,请求将被中断 timeout:1000, //'withCredentials’表示跨域请求时是否需要使用凭证 withCredentials:false,//默认的 //'adapter'允许自定义处理请求,以使测试更轻松 //返回一个 promise并应用一个有效的响应(查阅[response docs](#response-api)). adapter:function(config){ /*。。*/ }, //'auth’表示应该使用HTTP基础验证,并提供凭据 //这将设置一个'Authorization'头,覆写掉现有的任意使用'headers'设置的自定义'Authorization'头 auth :{ username:‘janedoe', password:'s00pers3cret' }, //'responseType'表示服务器响应的数据类型,可以是'arraybuffer','blob', 'document','json','text','stream' responseType:'json',//默认的 //'xsrfCookieName'是用作xsrf token的值的cookie的名称 xsrfCookieName:'XSRF-TOKEN',//default //'xsrfHeaderName'是承载xsrf token的值的HTTP头的名称 xsrfHeaderName:'X-XSRF-TOKEN',//默认的 //'onUploadProgress'允许为上传处理进度事件 onUploadProgress:function(progressEvent){ //对原生进度事件的处理 }, 'maxContentLength'定义允许的响应内容的最大尺寸 maxContentLength:2000, //'validatestatus'定义对于给定的HTTP响应状态码是resolve或reject promise。如果'validatestatus'返回'true'(或者设置为'null'或'undefined'),promise 将被 resolve;否则,promise将被rejecte validateStatus:function(status){ return status>=200&&status<300;//默认的 }, //'maxRedirects'定义在node.js中follow的最大重定向数目 //如果设置为0,将不会follow任何重定向 maxRedirects:5,//默认的 //'httpAgent'和'httpsAgent'分别在node.js中用于定义在执行http和 https 时使用的自定义代理。允许像这样配置选项: //'keepAlive'默认没有启用 httpAgent:new http.Agent({keepAlive:true}), httpsAgent:new https.Agent({keepAlive:true}), //'proxy’定义代理服务器的主机名称和端口 //'auth’表示HTTP基础验证应当用于连接代理,并提供凭据 //这将会设置一个'proxy-Authorization'头,写掉已有的通过使用'header'设置的自定义'Proxy-Authorization'头 proxy:{ host:127.0.0.1', port:9000, auth::{ username:'mikeymike', password:'rapunz3l' } }, //'cancelToken'指定用于取消请求的cancel token cancelToken:new CancelToken(function(cancel){ }) } 6 创建实例 可以使用自定义配置新建一个axios实例,之后使用该实例向服务 端发起请求,就不用每次请求时重复设置选项了。使用axios.create 方法创建axios实例,代码如下: axios.create([config]) var instance =axios.create({ baseURL:'https://some-domain.com/api/', timeout:1000, headers:{'X-Custom-Header':'foobar'} }); 7 配置默认选项 使用axios请求时,对于相同的配置选项,可以设置为全局的 axios默认值。配置选项在Vue的main.js文件中设置,代码如下: axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization']= AUTH TOKEN; axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded'; 也可以在自定义实例中配置默认值,这些配置选项只有在使用该 实例发起请求时才生效。代码如下: //创建实例时设置配置的默认值 var instance =axios.create({ baseURL:'https://api.example.com' }): //在实例已创建后修改默认值 instance.defaults.headers.common['Authorization']= AUTH TOKEN; 配置会以一个优先顺序进行合并。先在lib/defaults.js中找到库 的默认值,然后是实例的defaults属性,最后是请求的config参数。 例如: //使用由库提供的配置的默认值来创建实例 //此时超时配置的默认值是'0' var instance =axios.create(); //覆写库的超时默认值 //现在,在超时前,所有请求都会等待2.5秒 instance.defaults.timeout=2500; //为已知需要花费很长时间的请求覆写超时设置 instance.get('/longRequest',{ timeout:5000 }); 8 拦截器 拦截器在请求或响应被then方法或catch方法处理前拦截它们,从 而可以对请求或响应做一些操作。示例代码如下: //添加请求拦截器 axios.interceptors.request.use(function(config){ //在发送请求之前做些什么 return config; },function(error){ //对请求错误做些什么 return Promise.reject(error); }); //添加响应拦截器 axios.interceptors,response.use(function(response){ //对响应数据做些什么 return response; },function (error){ //对响应错误做些什么 return Promise.reject(error); }); 如果想在稍后移除拦截器,可以执行下面代码: var myInterceptor =axios.interceptors,request.use(function(){/*...*/}); axios.interceptors.request.eject(myInterceptor); 可以为自定义axios实例添加拦截器: var instance =axios.create(); instance,interceptors.request.use(function(){/*...*/}); 9 Vue.js 3.0的新变化——替代Vue.prototype 在Vue.js 2.x版本中,使用axios的代码如下: import Vue from 'vue' import axios from 'axios' Vue.prototype.axios=axi0S; 在Vue.js 3.0版本中,使用app.config.globalProperties来代替 prototype,具体用法如下: import {createApp}from'vue'; import axios from 'axios'; const app =createpp(); app.config.globalProperties.axios =axios; 这里需要注意的是,config.globalProperties这个属性是应用自 己才有的,而mount会返回实例,无法实现全局挂载。因此在实施链式 写法的时候,需要先设置congfig.globalProperties,然后后再进行 mount(),所以下面的写法是错误的。 //错误示范 import {createApp} from 'vue'; import axios from 'axios'; const app=createApp().mount('#app');//先设置全局属性,再进行挂载 app.config.globalProperties.axios =axios; 10 综合案例——显示近7日的天气情况 本节将使用axios库请求天气预报的接口,在页面中显示近7日的 天气情况。具体代码如下: <template> <div class="hello"> <h2>{{city}}</h2> <h4>今天:{{date}}{{week}}</h4> <h4>{{message}}</h4> <ul> <li v-for="item in obj"> <div> <h3>{{item.date}}</h3> <h3>{{item.week}}</h3> <img :src="get(item.wea img)" alt=""> <h3>{{item.wea}}</h3> </div> </li> </u1> </div> </template> <script> export default { name:'HelloWorld' data(){ return{ City:"", obj :[], date:"", week:"", message:"" } }, methods :{ //定义qet方法,拼接图片的路径 get(sky){ return "durian/"+sky+".png" } }, created(){ this.get();//页面开始加载时调用get方法 var that=this; this.$axios.get("/api") .then(function(response){ //处理数据 that.city=response.data.city; that.obj=response.data.data; that.date=response.data.data[0].date; that.week=response.data.data[0].week; that.message=response.data.data[0].air tips; }) .catch(function(error){ console.log(error) }) } } </script> <style scoped> h2,h4 { text-align:center; } li{ float:left; list-style:none; width:200px; text-align:center; border:1px solid red; } </style> 在浏览器中运行axiosdemo项目,页面效果如图6所示。 11 疑难解惑 疑问1:如何将axios结合vue-axios插件一起使用? 如果想将axios结合vue-axios插件一起使用,该插件只是将axios 集成到Vue.js的轻度封装,本身不能独立使用。可以使用如下命令一 起安装axios和vue-axios。 npm install axios vue-axios 安装了vue-axios插件后,就不需要将axios绑定到Vue的原型链上 了。使用形式如下: import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios,axios)//安装插件 之后在组件内就可以通过this.axios来调用axios的方法发送请求 了。 疑问2:axios有哪些常用方法? axios的常用方法如下: axios.get(url[,config]):get请求用于列表和信息查询。 axios.delete(url[,config]):删除操作。 axios.post(url[,data[,config]]):post请求用于信息的添 加。 axios.put(url[,data[,config]]):更新操作。
安卓开发-数据请求库——axios
于 2024-04-23 00:04:51 首次发布