axios库的使用
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库的使用的更多相关文章
- 五、Vue:使用axios库进行get和post、用拦截器对请求和响应进行预处理、Mock(数据模拟)
一.axios [应用]进行请求和传表单 [axios中文档]:https://www.kancloud.cn/yunye/axios/234845 [vue-axios]:https://cn.vu ...
- 在使用Vue.js中使用axios库时,遇到415错误(不支持的媒体类型(Unsupported media type))
知识点:vue2.0中使用axios进行(put,post请求时),遇到415错误 解决办法:在axios的第三个参数config中,设置请求头信息'Content-Type': 'applicati ...
- 在使用Vue2.0中使用axios库时,遇到415错误
解决办法:在axios的第三个参数config中,设置请求头信息'Content-Type': 'application/json;charset=UTF-8' this.$http.post('re ...
- [web 前端] 封装简单的axios库
转载自https://blog.csdn.net/qq_35844177/article/details/78809499 1.新建http.js文件,封装axios get post 方法 impo ...
- JWT实战:使用axios+PHP实现登录认证
上一篇文中,我们学习了什么是JWT(Json Web Token),今天我们来结合实例给大家讲述JWT的实战应用,就是如何使用前端Axios与后端PHP实现用户登录鉴权认证的过程. 查看演示 下载源码 ...
- axios介绍与使用说明 axios中文文档
本周在做一个使用vuejs的前端项目,访问后端服务使用axios库,这里对照官方文档,简单记录下,也方便大家参考. Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node ...
- Axios源码深度剖析 - 替代$.ajax,成为xhr的新霸主
前戏 在正式开始axios讲解前,让我们先想想,如何对现有的$.ajax进行简单的封装,就可以直接使用原声Promise了? let axios = function(config){ return ...
- 【Axios】前端页面使用axios调用后台接口
项目基本情况 前端项目是用vue.js做的,前端起的服务URL:http://localhost:8080/ 后端项目是用Node.js做的,后端起的服务URL:http://localhost:30 ...
- axios 使用
<!DOCTYPE html> <html lang="en"> <head> {#导入静态文件#} {% load static %} < ...
随机推荐
- 很烦人的maven和gradle的jar缓存
1. 起因 a. 最近在学习大数据相关东西,自然就少不免去操作linux系统,更别说不敲命令 b. 然而那个配置软件时,很经常使用ln -s为一个软件目录(带着版本或者其他信息的长命名)创建别名(软连 ...
- [HBase Manual] CH2 Getting Started
Getting Started Getting Started 1. Introduction 2.Quick Start-Strandalone HBase 2.1 JDK版本选择 2.2 Get ...
- 从MySQL Bug#67718浅谈B+树索引的分裂优化(转)
原文链接:http://hedengcheng.com/?p=525 问题背景 今天,看到Twitter的DBA团队发布了其最新的MySQL分支:Changes in Twitter MySQL 5. ...
- 【转载】Elasticsearch 5.x 字段折叠的使用,广度搜索
https://elasticsearch.cn/article/132 备注,分组字段只能是 keyword或num类型,不能是text类型 在 Elasticsearch 5.x 有一个字段折叠( ...
- NuGet Packages are missing,This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.
错误内容 This project references NuGet package(s) that are missing on this computer. Use NuGet Package R ...
- 解决ubuntu下音乐播放器Rhythmbox乱码问题
两种解决方法 第一种是修改用户的环境变量 1.先打开主文件夹 cd /home/user #user是你的用户名然后编辑用户环境 2.sudo gedit .profile在打开的文件中添加: exp ...
- lua 中protobuf repeated 嵌套类 复合类型
PB基础知识科普 syntax = "proto2"; package PB; message Item { required string name = ; } message ...
- windows 驱动开发 MDL 内核层 用户层共享内存
参考资料 https://blog.csdn.net/wdykanq/article/details/7752909 http://blog.51cto.com/laokaddk/404584 内核层 ...
- Codeforces Round #531 (Div. 3)
A:瞎猜. #include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); i ...
- ZooKeeper注册中心安装详细步骤(单节点)
安装 Dubbo 注册中心 Dubbo 建议使用 Zookeeper 作为服务的注册中心. 注册中心服务器(192.168.3.71)配置,安装 Zookeeper: 1. 修改操作系统的/etc/h ...