axios使用初涉
看vue的时候,vue2.0推荐使用axios做http请求,今天就学一下axios基本使用。
安装 axios
推荐npm方法(npm是node.js环境下的包管理器):
npm install axios
非常任性,只推荐这一种安装方法,强迫乃们使用这种便捷的方式。觉得npm慢?或者根本无回应?下面教大家更换电脑源npm。
目前接触到最多的就是淘宝npm镜像: http://npm.taobao.org/
镜像,我的理解是复制了一份国外源地址的代码等到自己的国内服务器,并且及时更新,这样用户去国内服务器访问即可加快访问速度。(不知道理解的对不对,欢迎指正)
安装淘宝镜像定制命令cnpm
$ npm install -g cnpm --registry=https://registry.npm.taobao.org $ cnpm install [模块名称] //安装模块 $ cnpm sync connect //同步模块 //支持npm除了publish之外的所有命令
so,第一步的安装axios你可以换成:
cnpm install axios
axios基本用法:
axios get请求之参数写在链接里:
axios.get('http://p.haoservice.com/Utility/GetProductList?key=8682dcb1b5c5488d84c10eb1767de0c5')
.then(function (res) {
console.log("请求成功:"+JSON.stringify(res))
})
.catch(function (error) {
console.log("请求失败:"+JSON.stringify(error))
})
axios get请求之参数写在params里:
axios.get('http://p.haoservice.com/Utility/GetProductList',{
params:{
key:'8682dcb1b5c5488d84c10eb1767de0c5'
}
})
.then(function (res) {
console.log("请求成功:"+JSON.stringify(res))
})
.catch(function (error) {
console.log("请求失败:"+JSON.stringify(error))
})
axios post请求:
axios.post('http://p.haoservice.com/Utility/GetProductList',{
key:'8682dcb1b5c5488d84c10eb1767de0c5'
})
.then(function (res) {
console.log("请求成功:"+JSON.stringify(res))
})
.catch(function (error) {
console.log("请求失败:"+JSON.stringify(error))
})
axios 自己配置参数生成请求:
axios({
method:'post',//方法
url:'/user/12345',//地址
data:{//参数
firstName:'Fred',
lastName:'Flintstone'
}
});
多重并发请求(这个厉害):
function getUserAccount(){
return axios.get('/user/12345');
}
function getUserPermissions(){
return axios.get('/user/12345/permissions');
}
axios.all([getUerAccount(),getUserPermissions()])
.then(axios.spread(function(acc,pers){ //spread方法相当于拆分数组
//两个请求现在都完成
console.log(acc)
console.log(pers)
}));
axios提供的请求方式(对照上面的几个实例,config配置信息:一个对象包含key:value格式的配置参数):
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]])
axios提供的多重并发方法(参考上面实例):
axios.all(iterable)
axios.spread(callback)
axios 配置参数列表:
{
// 请求地址
url: '/user',
// 请求类型
method: 'get',
// 请根路径
baseURL: 'http://www.mt.com/api',
// 请求前的数据处理
transformRequest:[function(data){}],
// 请求后的数据处理
transformResponse: [function(data){}],
// 自定义的请求头
headers:{'x-Requested-With':'XMLHttpRequest'},
// URL查询对象
params:{ id: 12 },
// 查询对象序列化函数
paramsSerializer: function(params){ }
// request body
data: { key: 'aa'},
// 超时设置s
timeout: 1000,
// 跨域是否带Token
withCredentials: false,
// 自定义请求处理
adapter: function(resolve, reject, config){},
// 身份验证信息
auth: { uname: '', pwd: '12'},
// 响应的数据格式 json / blob /document /arraybuffer / text / stream
responseType: 'json',
// xsrf 设置
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
// 下传和下载进度回调
onUploadProgress: function(progressEvent){
Math.round( (progressEvent.loaded * 100) / progressEvent.total )
},
onDownloadProgress: function(progressEvent){},
// 最多转发数,用于node.js
maxRedirects: 5,
// 最大响应数据大小
maxContentLength: 2000,
// 自定义错误状态码范围
validateStatus: function(status){
return status >= 200 && status < 300;
},
// 用于node.js
httpAgent: new http.Agent({ keepAlive: treu }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 用于设置跨域请求代理
proxy: {
host: '127.0.0.1',
port: 8080,
auth: {
username: 'aa',
password: '2123'
}
},
// 用于取消请求
cancelToken: new CancelToken(function(cancel){})
}
axios 响应数据:
{
// 服务器回应的数据将被包在data{}中,这点需要注意
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
// All header names are lower cased
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}
}
axios请求数据格式(较为关键的一点):
//axios串联js对象为JSON格式。为了发送application/x-wwww-form-urlencoded格式数据 //浏览器中使用URLSearchParams
var params = new URLSearchParams();
params.append('param1','value1');
params.append('param2','value2');
axios.post('/foo',params);
//使用qs格式化数据
var qs = require('qs');
axios.post('/foo', qs.stringify({'bar':123}));
更多详细用法,官方文档写的灰常灰常详细,不必乱找资料。 官网传送门: https://www.npmjs.com/package/axios
一片不错的文档翻译: https://segmentfault.com/a/1190000008470355?utm_source=tuicool&utm_medium=referral
axios使用初涉的更多相关文章
- 为什么axios请求接口会发起两次请求
之前在使用axios发现每次调用接口都会有两个请求,第一个请求时option请求,而且看不到请求参数,当时也没注意,只当做是做了一次预请求,判断接口是否通畅,但是最近发现并不是那么回事. 首先我们知道 ...
- axios基本用法
vue更新到2.0之后,作者就宣告不再对vue-resource更新,而是推荐的axios,前一段时间用了一下,现在说一下它的基本用法. 首先就是引入axios,如果你使用es6,只需要安装axios ...
- Struts2拦截器初涉
Struts2拦截器初涉 正在练习struts,本例是从一个pdf上摘抄的例子,那本pdf都不知道叫什么名字,不过感觉很适合初学者. 在这里要实现一个简单的拦截器"GreetingInter ...
- Axios、Lodash、TweenJS
Axios是一个基于promise的HTTP库 http://chuansong.me/n/394228451820 Lodash是一个JavaScript的函数工具集 http://www.css8 ...
- 初涉SQL Server性能问题(4/4):列出最耗资源的会话
在上3篇文章里,我们讨论了列出反映服务器当前状态的不同查询. 初涉SQL Server性能问题(1/4):服务器概况 初涉SQL Server性能问题(2/4):列出等待资源的会话 初涉SQL Ser ...
- 初涉SQL Server性能问题(3/4):列出阻塞的会话
在 初涉SQL Server性能问题(2/4)里,我们讨论了列出等待资源或正运行的会话脚本.这篇文章我们会看看如何列出包含具体信息的话阻塞会话清单. /************************ ...
- 初涉SQL Server性能问题(2/4):列出等待资源的会话
在初涉SQL Server性能问题(1/4)里,我们知道了如何快速检查服务器实例上正运行的任务数和IO等待的任务数.这个是轻量级的脚本,不会给服务器造成任何压力,即使服务器在高负荷下,也可以正常获得结 ...
- 【AS3 Coder】任务七:初涉PureMVC——天气预报功能实现
转自:http://www.iamsevent.com/post/36.html AS3 Coder]任务七:初涉PureMVC——天气预报功能实现 使用框架:AS3任务描述:了解PureMVC框架使 ...
- 初涉JavaScript模式系列 阶段总结及规划
总结 不知不觉写初涉JavaScript模式系列已经半个月了,没想到把一个个小点进行放大,竟然可以发现这么多东西. 期间生怕对JS的理解不到位而误导各位,读了很多书(个人感觉JS是最难的oo语言),也 ...
随机推荐
- 回归到jquery
最近在做一个公司的老产品的新功能,使用原来的技术框架,jquery和一堆插件,使用jquery的话,灵活性是有了,但是对于一个工作了3年多的我来说,很low,没什么成就感,技术本身比较简单,但是业务的 ...
- Centos7.4下安装Mysql8.0.15
一.下载Mysql Mysql下载地址:https://dev.mysql.com/downloads/mysql/ 二.卸载Linux自带的mariadb 安装Mysql之前需要卸载maria ...
- Monkey and Banana
Monkey and BananaTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...
- CSS外边距合并&块格式上下文
前言问题Margin Collapsing 外边距合并Block Formatting Context 块格式化上下文解决方案参考 前言 之前在前端开发的过程中,都没有遇到外边距合并的问题(其实是因为 ...
- github里如何删除一个repository仓库
高手请绕行,新手往下走. 作为一个刚接触github(https://github.com/)的新手,除了感叹开源的丰富和强大之外,自己肯定也想试用一下,因此申请帐号神马的.今天自己创建一个Repos ...
- Linux网络编程服务器模型选择之并发服务器(下)
前面两篇文章(参见)分别介绍了循环服务器和简单的并发服务器网络模型,我们已经知道循环服务器模型效率较低,同一时刻只能为一个客户端提供服务,而且对于TCP模型来说,还存在单客户端长久独占与服务器的连接, ...
- 【Ubuntu】安装配置apahce
安装apachesudo apt-get install apache2 安装目录 /etc/apache2配置文件 /etc/apache2/apache2.conf默认网站根目录 /var/www ...
- C# this关键字(给底层类库扩展成员方法)
本文参考自唔愛吃蘋果的C#原始类型扩展方法—this参数修饰符,并在其基础上做了一些细节上的解释 1.this作为参数关键字的作用 使用this关键字,可以向this关键字后面的类型添加扩展方法,而无 ...
- 网站变灰css
html{ filter: grayscale(100%); -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-fi ...
- Spring由于web配置导致的spring配置文件找不到的问题的解决方案
在把某项技术整合到Spring中的时候,我们时常会发现报如下错误: org.springframework.beans.factory.BeanCreationException: Error cre ...