axios是基于Promise 用于浏览器和 nodejs 的 HTTP 客户端;可以用在webpack + vuejs 的项目中

原文 https://github.com/axios/axios

1、example

1.1、get请求

axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
}); //换种方式
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
}); //从远程获取图片
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

1.2、post请求

axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

因axios post数据采用的是 Content-Type: 'application/x-www-form-urlencoded',所以后端是接受不到json格式的数据的

解决方法:引入qs库,发送请求之前将数据qs.stringify(data),是为了将数据变成类似title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3这种格式

1.2.1. application/x-www-form-urlencoded

POST http://www.example.com HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=utf-8
title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3

1.2.2 form-data

POST http://www.example.com HTTP/1.1
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="text"
title
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="file"; filename="chrome.png"
Content-Type: image/png
PNG ... content of chrome.png ...
------WebKitFormBoundaryrGKCBY7qhFd3TrwA--

1.2.3 application/json

POST http://www.example.com HTTP/1.1
Content-Type: application/json;charset=utf-8 {"title":"test","sub":[1,2,3]}

1.2.4 text/xml

POST http://www.example.com HTTP/1.1
Content-Type: text/xml <!--?xml version="1.0"?-->
<methodcall>
<methodname>examples.getStateName</methodname>
<params>
<param>
<value><i4>41</i4></value>
</param>
</params>
</methodcall>
>

1.3、并发请求

function getUserAccount() {
return axios.get('/user/12345');
} function getUserPermissions() {
return axios.get('/user/12345/permissions');
} axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function(acct, perms) { }));

2 API

2.1 发送请求配置config

{
url:'/user',
method:`get`, //`baseURL`如果`url`不是绝对地址,那么将会加在其前面,当axios使用相对地址时这个设置非常方便
baseURL:'http://some-domain.com/api/', //`transformRequest`允许请求的数据在传到服务器之前进行转化。
//这个只适用于`PUT`,`GET`,`PATCH`方法。
//数组中的最后一个函数必须返回一个字符串或者一个`ArrayBuffer`,或者`Stream`,`Buffer`实例,`ArrayBuffer`,`FormData`
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:{
firstName:'fred'
},
//`timeout`定义请求的时间,单位是毫秒。
//如果请求的时间超过这个设定时间,请求将会停止。
timeout:1000, //`withCredentials`表明是否跨网站访问协议,
//应该使用证书
withCredentials:false //默认值 //`adapter`适配器,允许自定义处理请求,这会使测试更简单。
//返回一个promise,并且提供验证返回(查看[response docs](#response-api))
adapter:function(config){
/*...*/
}, //`auth`表明HTTP基础的认证应该被使用,并且提供证书。
//这个会设置一个`authorization` 头(header),并且覆盖你在header设置的Authorization头信息。
auth:{
username:'janedoe',
password:'s00pers3cret'
}, //`responsetype`表明服务器返回的数据类型,这些类型的设置应该是
//'arraybuffer','blob','document','json','text',stream'
responsetype:'json', //`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 的详细部分)
cancelToken: new CancelToken(function(cancel){
})
} //reponse 应该包括的内容
{
data: {},
status: 200,
statusText: 'OK',
headers: {},
config: {},
request: {}
}

2.2 获取数据request方法

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]])

2.3 拦截

//发送request之前
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);
});

axios库的使用的更多相关文章

  1. 五、Vue:使用axios库进行get和post、用拦截器对请求和响应进行预处理、Mock(数据模拟)

    一.axios [应用]进行请求和传表单 [axios中文档]:https://www.kancloud.cn/yunye/axios/234845 [vue-axios]:https://cn.vu ...

  2. 在使用Vue.js中使用axios库时,遇到415错误(不支持的媒体类型(Unsupported media type))

    知识点:vue2.0中使用axios进行(put,post请求时),遇到415错误 解决办法:在axios的第三个参数config中,设置请求头信息'Content-Type': 'applicati ...

  3. 在使用Vue2.0中使用axios库时,遇到415错误

    解决办法:在axios的第三个参数config中,设置请求头信息'Content-Type': 'application/json;charset=UTF-8' this.$http.post('re ...

  4. [web 前端] 封装简单的axios库

    转载自https://blog.csdn.net/qq_35844177/article/details/78809499 1.新建http.js文件,封装axios get post 方法 impo ...

  5. JWT实战:使用axios+PHP实现登录认证

    上一篇文中,我们学习了什么是JWT(Json Web Token),今天我们来结合实例给大家讲述JWT的实战应用,就是如何使用前端Axios与后端PHP实现用户登录鉴权认证的过程. 查看演示 下载源码 ...

  6. axios介绍与使用说明 axios中文文档

    本周在做一个使用vuejs的前端项目,访问后端服务使用axios库,这里对照官方文档,简单记录下,也方便大家参考. Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node ...

  7. Axios源码深度剖析 - 替代$.ajax,成为xhr的新霸主

    前戏 在正式开始axios讲解前,让我们先想想,如何对现有的$.ajax进行简单的封装,就可以直接使用原声Promise了? let axios = function(config){ return ...

  8. 【Axios】前端页面使用axios调用后台接口

    项目基本情况 前端项目是用vue.js做的,前端起的服务URL:http://localhost:8080/ 后端项目是用Node.js做的,后端起的服务URL:http://localhost:30 ...

  9. axios 使用

    <!DOCTYPE html> <html lang="en"> <head> {#导入静态文件#} {% load static %} < ...

随机推荐

  1. webstorm11.0下载地址和webstorm11.0破解程序patcher.exe下载使用方法说明 前端IDE工具的利器

    20160107以下亲测可行. webstorm11.0下载地址:http://www.fxxz.com/soft/109234.html webstorm11.0下载安装破解使用说明: 下载完Web ...

  2. 对于 url encode decode js 和 c# 有差异

    在js对一个值进行解码使用:decodeURIComponent,编码使用:encodeURIComponent

  3. VS code配置go语言开发环境之自定义快捷键及其对应操作

    VS code 配置 自定义快捷键 及其对应操作   由于 vs code 的官方 go 插件不支持像 goland 一样运行当前 go 文件, 只能项目 或者 package 级别地运行, 因此有必 ...

  4. 【MySQL (六) | 详细分析MySQL事务日志redo log】

    Reference:  https://www.cnblogs.com/f-ck-need-u/archive/2018/05/08/9010872.html 引言 为了最大程度避免数据写入时 IO ...

  5. JavaWeb过滤器.监听器.拦截器-原理&区别(转)

    1.拦截器是基于java的反射机制的,而过滤器是基于函数回调 2.过滤器依赖与servlet容器,而拦截器不依赖与servlet容器 3.拦截器只能对action请求起作用,而过滤器则可以对几乎所有的 ...

  6. 微软Windows10LTSC2019官方三月更新版镜像

    何谓 Windows 10 LTSC?其实,LTSC 是 Long Term Support Channel 的缩写,翻译一下就是“长期服务分支”. Windows 10 LTSC 实际上就是微软官方 ...

  7. JS对象与Dom对象与jQuery对象之间的区别

    前言 通过问题看本质: 举例: js的写法:document.getElementById('save').disabled=true; 在jquery中我是这样写的 $("#save&qu ...

  8. MapReduce原理

    MapReduce原理 WordCount例子 用mapreduce计算wordcount的例子: package org.apache.hadoop.examples; import java.io ...

  9. 某公司面试java试题之【一】,看看吧,说不定就是你将要做的题

  10. CleanAop使用笔记

    前言,本(ˇˍˇ) 想用PostSharp做case,但是破解不成功,所以在github里找了一个CleanAop 地址: https://github.com/Jarvin-Guan/CleanAO ...