简介
axios是vue全家桶中的vue-resource不再维护后被推荐出来并逐渐流行。
axos是一个基于Promise用于浏览器和nodejs的HTTP客户端,本身具有的特征:
- 从浏览器中创建XMLHttpRequest
- 从nodejs发出http请求
- 支持Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止CSRF/XSRF
引入方式
npm i axios
或
cnpm i axios
或
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
使用
执行get
axios.get('/user?ID=123456').then(function(response){
console.log('gooooooood');
}).catch(function(error){
console.log(error);
})
//还可以通过prams对象传递参数
axios.get('./user',{
params:{
id:2
}
}).then(function(response){
console.log("goooood");
}).catch(function(error){
console.log(error);
})
执行post
axios.post('/user',{
first:2,
last:4
})
.then(function(response){
console.log();
}).catch(function(error){
console.log(error);
})
执行多个并发请求
function getUserAccount(){
return axios.get('./user/123');
}
function getUserPermissions(){
return axios.get('/user/123/permissions')
}
axios.all([getUserAccount(),getUserPermissions()])
.then(axios.spread(function(){
//两个请求现已完成
}))
API
1)axios(config)
axios({
methodd:'post',
url:'...',
data:{
firstname:'fred',
lastname:'anne'
}
})
2) axios(url[,config])
axios('/user/123')
3)请求方法别名
- 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]])
使用别名时,不需要在config中指定url,method,和data属性
4)并发
- axios.all(itarable)
- axios.spread(callback)
5)创建实例
axios.create([config])
const instance=axios.create({
baseURL:'https://some.com/a',
timeout:1000,
headers:{ 'X-Custom-Header':'foobar' }
})
5)实例方法
可用的实例方法如下。指定的配置将与实例配置合并(问题是怎么合并?)
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
请求配置
以下的配置选项可以用来发出请求。只有url
是必选项。如果方法没有指定,默认请求为GET方法。
{
url:'/url',
method:'get',
baseURL:'...',//前置于url,除非url是绝对路径
transformRequest:[function(data,headers){
return data;
}],
//在请求被发送到服务端之前,允许改变请求数据;仅适用于请求方法PUT ,POST,PATCH
//数组中的最后一个方法必须返回一个字符串或者一个Buffer,ArrayBuffer,FormData的实例,或者Stream
//你也可以修改请求头对象
transfromResponse:[function(data){
return data;
}],
//允许修改响应数据,在响应数据被传入then和catch函数之前
headers:{'X-Request-With':'XMLHttpRequest'},
//自定义请求头
params:{
ID:2
},
//params是与请求头一起发送的url参数
//必须是一个大普通的对象或者URLSearchParams对象
paramsSerializer:function(params){
return Qs.strngify(params,{arrayFormat:'brackets'})
},
//负责序列化params的可选函数
//(e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
data:{
firstname:'Fred'
},
//data是作为请求主体发送的对象
//**仅适用于PUT,POST,PATCH方法**
//当'transformRequest'没有设置的时候,必须是以下数据类型之一:
//-string,plain object,ArrayBuffer,ArrayBufferView,URLSearchParams
//-Browser only:FormData,File,Blob
//-Node only:Stream,Buffer
timeout:1000,
withCredentials:false,
//是否跨站点请求控制
adapter:function(config){
},
//允许自定义请求处理,使得测试更加容易
auth:{
username:'jane',
password:'jjk34g'
},
//auth表明必须使用http基本认证,并且提供凭证。
//这将设置一个'Authorization'头,覆盖任何已有的值
responseType:'json',
//响应的数据类型可以是:
//'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseEncoding:'utf8',
//编码设置忽略responseType为stream或客户端请求
xsrfCookieName:'XSRF-TOKEN',//用作XSRF token的cookie名称,默认值为XSRF-TOKEN
xsrfHeaderName:'XSRF-TOKEN',//携带XSRF-TOKEN值的http请求头名称。默认值为XSRF-TOKEN
onUploadProgress:function(progressEvent){
}, //允许处理上传的进度事件
onDownloadProgress:function(progressEvent){
}, //允许处理下载的进度事件
maxContentLength:2000, //以允许的字节数定义http响应内容的最大值
validateStatus:function(status){
return status>=200 && status <300;
}, //定义是否resolved或reject给定的promise
//HTTP响应状态码,如果返回true或设置为返回null或undefined,promise将被resolved;否则将被rejected。
maxRedirects:5, //定义nodejs里最大重定向次数;如果设为0,将不允许重定向
socketPath:null,
//定义在nodejs里使用的UNIX套接字
httpAgent:new http.Agent({ keepAlive:true }),
httpsAgent:new https.Agent({ keepAlive:true }),
//定义了执行http和https请求时要使用的自定义代理。特别的,在nodejs里允许添加{ keepAlive:true }选项,默认是不允许的。
proxy:{
host:'127.0.0.1',
port:9000,
auth:{
username:'nike',
pasword:'123456'
}
},
//定义代理服务器的主机名,端口。auth表明必须使用HTTP基本认证来链接到代理,并且提供凭证。
//这将会设置一个请求头'Proxy-Authorization',覆盖所有已存在的值
cancelToken:new CancelToken(function(cancel){})
//定义了一个cancel token可以用来取消请求(参考Cancellation节)
}
响应模式
一个请求的响应将包含如下内容
{
data:{},
status:200,
statuText:'OK',
headers:{},
config:{},
request:{}//产生这个响应的request.它是node.js中的最后一个ClientRequest实例(在重定向中)和
//浏览器的XMLHttpRequest实例.
}
当使用then时,你要使用以下的模式获取response的内容:
axios.get('./uer/123').then(function(response){
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
})
当使用catch或将拒绝回调作为第二个参数传递时,响应将通过错误对象提供,如处理错误部分中所述。