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. iOS Xcode 10: Multiple commands produce

    Xcode自动升级到10.0 1.编译的时候报错:Multiple commands produce 解决办法:File -> Workspace Setting -> build sys ...

  2. jinfo

    jinfo是jdk自带的命令,用来查看.修改jvm的配置参数. [weblogic@host bin]$ jinfo-bash: jinfo: command not found[weblogic@h ...

  3. 理解REST和RPC

    REST 越来越多的人开始意识到,网站即软件,而且是一种新型的软件. 网站开发,完全可以采用软件开发的模式.但是传统上,软件和网络是两个不同的领域,很少有交集:软件开发主要针对单机环境,网络则主要研究 ...

  4. 通过端口映射连接不同网段的oracle

    oracle在内网,只有特殊机器能访问,通过做端口映射,可以以这个特殊机器作为“跳板”完成本机对远程oracle的连接. “跳板”机器是windows,需要在该机器上执行netsh命令: netsh ...

  5. 一对一voip,直播连麦,在线会议,兼容webrtc,IM音视频

    功能 IM消息系统 一对一 高清音视频实时通信,可无缝切换P2P传输,节省服务器带宽 一对多互动直播 多对多在线会议 手机实时录屏传输 高度定制化 网络检测,动态码率与动态帧率,抗网络抖动,微信级效果 ...

  6. WebSocket学习与使用

    1.WebSocket是什么 WebSocket是一种在单个TCP连接上进行全双工通信的协议,其目的是在浏览器和服务器之间建立一个不受限的双向通信的通道,使得服务器可以主动发送消息给浏览器.在HTML ...

  7. list add对象踩的坑

    list 添加对象时,没有把new object写到循环体里,导致最后添加了相同的一个对象: public List<goods> find(String goodsname) { Lis ...

  8. DOTween-Ease缓动函数

    Ease.InQuad 不知道Quad代表什么意思  Ease.InQuart 有1/4的时间是没有缓动.  Ease.InQuint, 是1/5时间没有缓动.  Ease.InExpo 一直很平缓, ...

  9. 通过User-agent进行SQL注入

    声明:本文由Bypass整理并翻译,仅用于安全研究和学习之用. 文章来源:https://hackerone.com/reports/297478 我发现了一个SQL注入漏洞 /dashboard/d ...

  10. 《转载》JVM垃圾回收机制

    本文转载自ImportNew - 郑雯 每个Java程序员迟早都会碰到下面这个错误: java.lang.OutOfMemoryError 这个时候一般会建议采用如下方式解决这个错误: 增加MaxPe ...