看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使用初涉的更多相关文章

  1. 为什么axios请求接口会发起两次请求

    之前在使用axios发现每次调用接口都会有两个请求,第一个请求时option请求,而且看不到请求参数,当时也没注意,只当做是做了一次预请求,判断接口是否通畅,但是最近发现并不是那么回事. 首先我们知道 ...

  2. axios基本用法

    vue更新到2.0之后,作者就宣告不再对vue-resource更新,而是推荐的axios,前一段时间用了一下,现在说一下它的基本用法. 首先就是引入axios,如果你使用es6,只需要安装axios ...

  3. Struts2拦截器初涉

    Struts2拦截器初涉 正在练习struts,本例是从一个pdf上摘抄的例子,那本pdf都不知道叫什么名字,不过感觉很适合初学者. 在这里要实现一个简单的拦截器"GreetingInter ...

  4. Axios、Lodash、TweenJS

    Axios是一个基于promise的HTTP库 http://chuansong.me/n/394228451820 Lodash是一个JavaScript的函数工具集 http://www.css8 ...

  5. 初涉SQL Server性能问题(4/4):列出最耗资源的会话

    在上3篇文章里,我们讨论了列出反映服务器当前状态的不同查询. 初涉SQL Server性能问题(1/4):服务器概况 初涉SQL Server性能问题(2/4):列出等待资源的会话 初涉SQL Ser ...

  6. 初涉SQL Server性能问题(3/4):列出阻塞的会话

    在 初涉SQL Server性能问题(2/4)里,我们讨论了列出等待资源或正运行的会话脚本.这篇文章我们会看看如何列出包含具体信息的话阻塞会话清单. /************************ ...

  7. 初涉SQL Server性能问题(2/4):列出等待资源的会话

    在初涉SQL Server性能问题(1/4)里,我们知道了如何快速检查服务器实例上正运行的任务数和IO等待的任务数.这个是轻量级的脚本,不会给服务器造成任何压力,即使服务器在高负荷下,也可以正常获得结 ...

  8. 【AS3 Coder】任务七:初涉PureMVC——天气预报功能实现

    转自:http://www.iamsevent.com/post/36.html AS3 Coder]任务七:初涉PureMVC——天气预报功能实现 使用框架:AS3任务描述:了解PureMVC框架使 ...

  9. 初涉JavaScript模式系列 阶段总结及规划

    总结 不知不觉写初涉JavaScript模式系列已经半个月了,没想到把一个个小点进行放大,竟然可以发现这么多东西. 期间生怕对JS的理解不到位而误导各位,读了很多书(个人感觉JS是最难的oo语言),也 ...

随机推荐

  1. win7 下如何安装 Microsoft Web Application Stress Tool

    Microsoft Web Application Stress Tool是一个简单易用的性能压力测试工具,但因为其诞生的年代较早,在目前的win7系统下运行,会存在一些兼容性的问题,以下是我在实际使 ...

  2. 这是一次 docker 入门实践

    前言 其实接触 docker 也有一段时间了,但是一直没有做下总结,现在网上关于 docker 的介绍也有很多了,本着好记性不如烂笔头的原则,还是自己再记录一波吧. 实现目标 安装 docker ce ...

  3. (Lua) C++ 加入 Lua 環境擴充應用強度

    Lua 在網上有非常多的介紹,就是一個小而巧的語言,可以放入嵌入式系統 也可以在一般的應用上非常強大,這邊主要記錄如何讓Lua加入C++裡頭應用 Lua source code 是以 C 語言下去編寫 ...

  4. Ubuntu 16.04防火墙

    防火墙(ufw) 说明:简单版本的防火墙,底层依赖于iptables. 安装:sudo apt-get install ufw 查看状态:sudo ufw status 开启/关闭:sudo ufw ...

  5. bingoyes' tiny dream

    Gauss Elimination bool Gauss(){ int now=1,nxt; double t; R(i,1,n){ //enumerate the column for(nxt=no ...

  6. linux 和 windows 安装composer

    在 Linux 和 Mac OS X 中可以运行如下命令: curl -sS https://getcomposer.org/installer | phpmv composer.phar /usr/ ...

  7. PHP 浮点数 转化 整数方法对比 ceil,floor,round,intval,number_format

    ceil,floor,round,intval,number_format - 执行1000W此效率对比 Header("Content-Type:text/html;charset=utf ...

  8. WebDriver+TestNG的一个典型例子

    想让测试更加灵活,1. 可以配置使用任意支持的浏览器进行测试:2. 配置所有Google的URL:3. 配置搜索的关键字.修改后的代码: public class GoogleTest { WebDr ...

  9. 关于js语法(运算中出现无限大的问题)本身的错误的解决方案

    错误原因: 一是 JavaScript 浮点数计算的 Bug, 另一个是和计算机最终转换成二进制计算有关系 解决方案: 第一种就是利用JavaScript 的toFixed(n) 方法,直接获取N 位 ...

  10. C 标准库 - string.h之memcpy使用

    memcpy Copy block of memory Copies the values of num bytes from the location pointed to by source di ...