javascript http库axios
还是那个开源项目中的代码看到的:
直接看axios官方的介绍吧,里面的用法介绍很全:
https://github.com/mzabriskie/axios
Installing
Using npm:
$ npm install axios
Using cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Example
Performing a GET
request
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
}); // Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Performing a POST
request
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Performing multiple concurrent requests
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) {
// Both requests are now complete
}));
。。。
Response Schema
The response for a request contains the following information.
{
// `data` is the response that was provided by the server
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: {}
}
When using then
, you will receive the response as follows:
axios.get('/user/12345')
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
When using catch
, or passing a rejection callback as second parameter of then
, the response will be available through the error
object as explained in the Handling Errors section.
Config Defaults
You can specify config defaults that will be applied to every request.
Global axios defaults
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Interceptors
You can intercept requests or responses before they are handled by then
or catch
.
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
}); // Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
If you may need to remove an interceptor later you can.
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
You can add interceptors to a custom instance of axios.
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
Handling Errors
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
You can define a custom HTTP status code error range using the validateStatus
config option.
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
Cancellation
You can cancel a request using a cancel token.
The axios cancel token API is based on the withdrawn cancelable promises proposal.
You can create a cancel token using the CancelToken.source
factory as shown below:
var CancelToken = axios.CancelToken;
var source = CancelToken.source(); axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
}); // cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the CancelToken
constructor:
var CancelToken = axios.CancelToken;
var cancel; axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
}); // cancel the request
cancel();
Note: you can cancel several requests with the same cancel token.
javascript http库axios的更多相关文章
- ABP(现代ASP.NET样板开发框架)系列之21、ABP展现层——Javascript函数库
点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之21.ABP展现层——Javascript函数库 ABP是“ASP.NET Boilerplate Project ...
- Webix JavaScript UI 库可以帮你构建跨平台的HTML5 和 CSS3 程序
XB 软件公司最近发布了JavaScript UI 库Webix ,其中包含的组件超过45个,用这些组件可以构建跟HTML5 和 CSS3 兼容的程序,这些程序不仅能在个人电脑上运行,还能用在iOS. ...
- ECharts-基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据可视化图表
ECharts http://ecomfe.github.com/echarts 基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据可视化图表.创新的拖拽重计算 ...
- 【精心推荐】几款实用的 JavaScript 图形图表库
一款好的图表插件不是那么容易找到的.最近项目里需要实现统计图表功能,所以在网上搜罗了一圈,找到一些不错的图表插件,分享大家.众多周知,图形和图表要比文本更具表现力和说服力.这里给大家精心推荐几款实用的 ...
- Vis.js – 基于浏览器的动态 JavaScript 可视化库
Vis.js 是一个动态的,基于浏览器的可视化库.该库被设计为易于使用,能处理大量的动态数据.该库由以下几部分组成:一是数据集和数据视图,基于灵活的键/值数据集,可以添加,更新和删除项目,订阅数据集变 ...
- 向 Web 开发人员推荐35款 JavaScript 图形图表库
图表是数据图形化的表示,通过形象的图表来展示数据,比如条形图,折线图,饼图等等.可视化图表可以帮助开发者更容易理解复杂的数据,提高生产的效率和 Web 应用和项目的可靠性. 在这篇文章中,我们收集了3 ...
- 几款实用的 JavaScript 图形图表库
一款好的图表插件不是那么容易找到的.最近项目里需要实现统计图表功能,所以在网上搜罗了一圈,找到一些不错的图表插件,分享大家.众多周知,图形和图表要比文本更具表现力和说服力.这里给大家精心推荐几款实用的 ...
- ECharts JavaScript图表库 ECharts
ECharts开源来自百度商业前端数据可视化团队,基于html5 Canvas,是一个纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据可视化图表.创新的拖拽重计算.数据视图.值 ...
- ABP展现层——Javascript函数库
ABP展现层——Javascript函数库 点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之21.ABP展现层——Javascript函数库 ABP是“ASP.N ...
随机推荐
- 使用Tslib在触摸屏上显示汉字【转】
转自:http://www.latelee.org/embedded-linux/use-tslib-to-display-chinese-character.html 终于到了在触摸屏上显示汉字了, ...
- 【 Zabbix 】nginx监控及故障重启服务
zabbix agentd 端配置: nginx.conf 配置: location /ngx_status { stub_status on; access_log off; allow 10.0. ...
- java的maven项目(三)私服的搭建(windows版)
1 私服 nexus 安装nexus 启动服务 启动失败的解决方法: 登录nexus 用户名/密码 admin/admin123 仓库类型 Virtual 虚拟仓库 Proxy 代 ...
- 通过Eclipse生成可运行的jar包
本来转自http://www.cnblogs.com/lanxuezaipiao/p/3291641.html 我是个追新潮的人,早早用上了MyEclipse10.最近需要使用Fat jar来帮我对一 ...
- docker官方文档中的dns,link,expose,publish
link是过时的了,尽量不要用. dns内部集成,也可以用外部. expose只是用于记录,并不真的. publish是否起作用,也要看情况,是否被占用端口. -------------------- ...
- (十六)MySQL集群galera实现
(1)环境介绍 galera官网:http://galeracluster.com/downloads/ # cat /etc/redhat-release CentOS Linux release ...
- 用JDBC操作MySQL——获取表的大小
JDBC中获取MySQL我们有时需要获得表的大小,这包括了表的行数和列数,我们可以分别用以下的方法得到: 假设我们得到了一个ResultSet对象rs,则操作如下: 读取结果集前获取行数: rs.la ...
- scrapy生成csv文件空行、csv文件打开乱码(解决方案)
一.scrapy生成csv文件会有多余的空行 当使用scrapy crawl testspider -o test.csv后,生成的默认csv文件每一行之间是有空行的,解决的方法是修改scrapy的源 ...
- 安装redis扩展
1.安装redis模块 wget https://codeload.github.com/phpredis/phpredis/zip/php7 unzip php7 cd phpredis-php7/ ...
- UVA GCD - Extreme (II)
discription Given the value of N, you will have to find the value of G. The definition of G is given ...