1.Axios的概念vue
axios 是一个基于 promise 的 HTTP 库,能够用在浏览器和 node.js 中。node
特色:jquery
安装nodejs(自带npm),安装cnpm(可选)ios
npm install -g cnpm --registry=https://registry.npm.taobao.org
初始化项目: git
npm init -y
Npm的方式安装axios github
npm i axios -D
1)、get请求ajax
let vueobj = this; axios.get('api/goodslists', { params: { "goodsid":"01003" } } ) .then(function (response) { console.log(response.data); vueobj.goodslist = response.data; //把获取到的数据赋给goodslist }) .catch(function (error) { console.log(error); });
2)、执行多个并发请求vue-router
getall:function(){ function getbooks(){ return axios.get('api/books'); } function getreaders(){ return axios.get('api/readers'); } axios.all([getbooks(), getreaders()]).then( axios.spread(function (books, readers) { //两个请求都完成后,调用该函数,第一个参数是第一个请求的结果,第二个参数是第二个请求的结果 console.log(books.data); console.log(readers.data); }) ); }
1)、axios函数:vuex
axios(config)。在config对象参数里,除了url外,其它的均可选的属性。
axios 可以在进行请求时的一些设置。如:
发起 get请求 let vueobj = this;npm
axios({ method:'get', url:'api/goodslists', params :{ "goodsid":"01003" } }) .then(function (response) { vueobj.goodslist = response.data; }) .catch(function (error) { console.log(error); });
2)、axios请求的别名:
为了方便,axios提供了全部请求方法的重命名支持,以下:
axios.request(config)
axios.get(url[,config])
axios.delete(url[,config])
axios.head(url[,config])
axios.post(url[,data[,config]])
axios.put(url[,data[,config]])
axios.patch(url[,data[,config]])
一、axios.request(config)
let vueobj = this; axios.request({ method:'get', url:'api/goodslists', params:{ "goodsid":"01002" } }) .then(function (response) { vueobj.goodslist = response.data; }) .catch(function (error) { console.log(error); });
2. axios.get(url[,config])
let vueobj = this; axios.get('api/goodslists', { params:{ "goodsid":"01003" } }) .then(function (response) { vueobj.goodslist = response.data; }) .catch(function (error) { console.log(error); });
3. Axios处理并发( Concurrency)
axios.all(iterable)//all函数执行全部的请求
axios.spread(callback)//处理响应回来的回调函数
代码:
getall:function(){ function getbooks(){ return axios.get('api/books'); } function getreaders(){ return axios.get('api/readers'); } axios.all([getbooks(), getreaders()]).then( axios.spread(function (books, readers) { //两个请求都完成后,调用该函数,第一个参数是第一个请求的结果,第二个参数是第二个请求的结果 console.log(books.data); console.log(readers.data); }) ); }
4.建立一个实例,实例方法
建立一个新的实例
axios.create([config])
实例方法
下面列出了一些实例方法。具体的设置将在实例设置中被合并。
axios#request(config)
axios#get(url[,config])
axios#delete(url[,config])
axios#head(url[,config])
axios#post(url[,data[,config]])
axios#put(url[,data[,config]])
axios#patch(url[,data[,config]])
代码:
一、建立axios实例
var instance = axios.create({ method:'get', url:'api/goodslists', params:{ "goodsid":"01002" } });
二、发送请求
instance.request() .then(function (response) { console.log(response.data); vueobj.goodslist = response.data; }) .catch(function (error) { console.log(error); });
//`url`是服务器连接,用来请求用 url:'/user', //`method`是发起请求时的请求方法 method:`get`, //`baseURL`若是`url`不是绝对地址,那么将会加在其前面。 //当axios使用相对地址时这个设置很是方便 //在其实例中的方法 baseURL:'http://some-domain.com/api/', //`transformRequest`容许请求的数据在传到服务器以前进行转化。 //这个只适用于`PUT`,`GET`,`PATCH`方法。 //数组中的最后一个函数必须返回一个字符串,一个`ArrayBuffer`,或者`Stream` transformRequest:[function(data){ //依本身的需求对请求数据进行处理 return data; }], //`transformResponse`容许返回的数据传入then/catch以前进行处理 transformResponse:[function(data){ //依须要对数据进行处理 return data; }], //`headers`是自定义的要被发送的头信息 headers:{'X-Requested-with':'XMLHttpRequest'}, //`params`是请求链接中的请求参数,必须是一个纯对象,或者URLSearchParams对象 params:{ ID:12345 }, //`paramsSerializer`是一个可选的函数,是用来序列化参数 //例如:(https://ww.npmjs.com/package/qs,http://api.jquery.com/jquery.param/) paramsSerializer: function(params){ return Qs.stringify(params,{arrayFormat:'brackets'}) }, //`data`是请求提须要设置的数据 //只适用于应用的'PUT','POST','PATCH',请求方法 //当没有设置`transformRequest`时,必须是如下其中之一的类型(不可重复?): //-string,plain object,ArrayBuffer,ArrayBufferView,URLSearchParams //-仅浏览器:FormData,File,Blob //-仅Node:Stream data:{ firstName:'fred' }, //`timeout`定义请求的时间,单位是毫秒。 //若是请求的时间超过这个设定时间,请求将会中止。 timeout:1000, //`withCredentials`代表是否跨域请求, //应该是用证书 withCredentials:false //默认值 //`adapter`适配器,容许自定义处理请求,这会使测试更简单。 //返回一个promise,而且提供验证返回(查看[response docs](#response-api)) adapter:function(config){ /*...*/ }, //`xsrfHeaderName` 是http头(header)的名字,而且该头携带xsrf的值 xrsfHeadername:'X-XSRF-TOKEN',//默认值 //`onUploadProgress`容许处理上传过程的事件 onUploadProgress: function(progressEvent){ //本地过程事件发生时想作的事 }, //`onDownloadProgress`容许处理下载过程的事件 onDownloadProgress: function(progressEvent){ //下载过程当中想作的事 }, //`maxContentLength` 定义http返回内容的最大容量 maxContentLength: 2000, //`validateStatus` 定义promise的resolve和reject。 //http返回状态码,若是`validateStatus`返回true(或者设置成null/undefined),promise将会接受;其余的promise将会拒绝。 validateStatus: function(status){ return status >= 200 && stauts < 300;//默认 }, //`httpAgent` 和 `httpsAgent`当产生一个http或者https请求时分别定义一个自定义的代理,在nodejs中。 //这个容许设置一些选选个,像是`keepAlive`--这个在默认中是没有开启的。 httpAgent: new http.Agent({keepAlive:treu}), httpsAgent: new https.Agent({keepAlive:true}), //`proxy`定义服务器的主机名字和端口号。 //`auth`代表HTTP基本认证应该跟`proxy`相链接,而且提供证书。 //这个将设置一个'Proxy-Authorization'头(header),覆盖原先自定义的。 proxy:{ host:127.0.0.1, port:9000, auth:{ username:'cdd', password:'123456' } }, //`cancelTaken` 定义一个取消,可以用来取消请求 //(查看 下面的Cancellation 的详细部分) cancelToke: new CancelToken(function(cancel){ }) }
2)、响应数据的格式:
{ //`data`是服务器的提供的回复(相对于请求) data{}, //`status`是服务器返回的http状态码 status:200, //`statusText`是服务器返回的http状态信息 statusText: 'ok', //`headers`是服务器返回中携带的headers headers:{}, //`config`是对axios进行的设置,目的是为了请求(request) config:{} }
使用 then ,你会接受打下面的信息
axios.get('/user/12345') .then(function(response){ console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); });
使用 catch 时,或者传入一个 reject callback 做为 then 的第二个参数,那么返回的错误信息将可以被使用。
你能够在请求或者返回被 then 或者 catch 处理以前对它们进行拦截。
1)、请求拦截器
axios.interceptors.request.use( function (config) {//config参数是请求的配置 config.url=‘api/goodslists’;//发送请求前,修改请求的url return config }, function (error) { console.log('请求失败') return Promise.reject(error) } );
2)、响应拦截器
axios.interceptors.response.use( function (response) {//response参数是响应对象 response.data.unshift({“goodsid”:“商品编号”,“goodsname”:“商品名称”,“goodsprice”:“商品价格”});//给响应的数据增长一个对象 return response; }, function (error) { console.log('响应出错') return Promise.reject(error) })
3)、请求的代码:
let vueobj = this; axios.request({ method:'get', url:'api/readers', params:{ "goodsid":"01002" } }) .then(function (response) { console.log(response.data); vueobj.goodslist = response.data; }) .catch(function (error) { console.log(error); });
Ajax:
ajax天然没必要说,最先出现的发送后端请求技术,隶属于原始js中,核心使用XMLHttpRequest对象,多个请求之间若是有前后关系的话,就会出现回调地狱。
Jquery Ajax:
是jQuery框架中的发送后端请求技术,因为jQuery是基于原始的基础上作的封装,因此,jquery Ajax天然也是原始ajax的封装
Fetch:
fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点像jQuery ajax。可是,必定记住fetch不是ajax的进一步封装,而是原生js。Fetch函数就是原生js,没有使用XMLHttpRequest对象。与XMLHttpRequest(XHR)相似,fetch()方法容许你发出AJAX请求。区别在于Fetch API使用Promise,所以是一种简洁明了的API,比XMLHttpRequest更加简单易用。
fetch("../students.json").then(function(response){ if(response.status!==200){ console.log("存在一个问题,状态码为:"+response.status); return; } //检查响应文本 response.json().then(function(data){ console.log(data); }); }).catch(function(err){ console.log("Fetch错误:"+err); })
mode属性用来决定是否容许跨域请求,以及哪些response属性可读。可选的mode属性值为 same-origin,no-cors(默认)以及 cores;
Response 也有一个type属性,它的值多是"basic","cors","default","error"或者"opaque";
function status(response){ if(response.status>=200 && response.status<300){ return Promise.resolve(response); }else{ return Promise.reject(new Error(response.statusText)); } } function json(response){ return response.json(); } fetch("../students.json",{mode:"cors"})//响应类型“cors”,通常为“basic”; .then(status)//能够连接方法
.then(json)
.then(function(data){
console.log("请求成功,JSON解析后的响应数据为:",data); })
.then(function(response){
console.log(response.headers.get('Content-Type')); //application/json
console.log(response.headers.get('Date')); //Wed, 08 Mar 2017 06:41:44 GMT
console.log(response.status); //200
console.log(response.statusText); //ok
console.log(response.type); //cors
console.log(response.url); //http://.../students.json })
.catch(function(err){
console.log("Fetch错误:"+err);
})
使用POST方法提交页面中的一些数据:将method属性值设置为post,而且在body属性值中设置须要提交的数据;
credentials属性决定了cookies是否能跨域获得 : "omit"(默认),"same-origin"以及"include";
var url='...'; fetch(url,{ method:"post",//or 'GET' credentials: "same-origin",//or "include","same-origin":只在请求同域中资源时成功,其余请求将被拒绝。
headers:{
"Content-type":"application:/x-www-form-urlencoded:charset=UTF-8"
},
body:"name=lulingniu&age=40"
})
.then(status) .then(json) //JSON进行解析来简化代码 .then(function(data){ console.log("请求成功,JSON解析后的响应数据为:",data); }) .catch(function(err){ console.log("Fetch错误:"+err); });
浏览器支持:
目前Chrome 42+, Opera 29+, 和Firefox 39+都支持Fetch。微软也考虑在将来的版本中支持Fetch。
讽刺的是,当IE浏览器终于微响应实现了progress事件的时候,XMLHttpRequest
也走到了尽头。 目前,若是你须要支持IE的话,你须要使用一个polyfill库。
promises介绍:
这种写法被称为composing promises, 是 promises 的强大能力之一。每个函数只会在前一个 promise 被调用而且完成回调后调用,而且这个函数会被前一个 promise 的输出调用;
axios:
axios不是原生JS的,须要进行安装,它不带能够在客户端使用,也能够在nodejs端使用。Axios也能够在请求和响应阶段进行拦截。一样也是基于promise对象的。具体参照axios的概念
Vue 本来有一个官方推荐的 ajax 插件 vue-resource,可是自从 Vue 更新到 2.0 以后,尤雨溪宣布中止更新vue-resource,并推荐你们使用axios以后,愈来愈多的 Vue 项目,都选择 axios 来完成 ajax 请求,而大型项目会使用 Vuex 来管理数据
以前一直使用的是 vue-resource插件,在主入口文件引入import VueResource from 'vue-resource'
以后,直接使用Vue.use(VueResource)
以后便可将该插件全局引用了;
初用axios时,无脑的按照上面的步骤进行全局引用,结果当时是惨惨的。
看了看文档,Axios 是一个基于 promise 的 HTTP 库
axios并无install 方法,因此是不能使用vue.use()方法的。
那么难道每一个文件都要来引用一次?解决方法有不少种:
1.结合 vue-axios使用
2. axios 改写为 Vue 的原型属性
3.结合 Vuex的action
看了vue-axios的源码,它是按照vue插件的方式去写的。那么结合vue-axios,就能够去使用vue.use方法了
首先在主入口文件main.js中引用
import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios,axios);
以后就可使用了,在组件文件中的methods里去使用了
getNewsList(){ this.axios.get('api/getNewsList').then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); }) },
首先在主入口文件main.js中引用,以后挂在vue的原型链上
import axios from 'axios'
Vue.prototype.$ajax= axios
在组件中使用
this.$ajax.get('api/getNewsList').then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); })
结合 Vuex的action
在vuex的仓库文件store.js中引用,使用action添加方法
import Vue from 'Vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) const store = new Vuex.Store({ // 定义状态 state: { user: { name: 'xiaoming' } }, actions: { // 封装一个 ajax 方法 login (context) { axios({ method: 'post', url: '/user', data: context.state.user }) } } }) export default store
在组件中发送请求的时候,须要使用 this.$store.dispatch
methods: { submitForm () { this.$store.dispatch('login') } }
使用vue2.0+mintUI+axios+vue-router:https://github.com/Stevenzwzhai/vue-mobile-application
使用vue2.0+elementUI+axios+vue-router:https://github.com/Stevenzwzhai/vue2.0-elementUI-axios-vueRouter