axios API速查表
原来jq自带ajax方法,但是近期项目用vue,在vue项目中发送ajax请求原来用vue resource,现在更推荐使用axios,因为axios和vue更配!
GET 请求
// 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);
});
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
POST 请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Send a POST request
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([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
创建实例
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
Response
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);
});
Config
// 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';
// Custom instance defaults
// Set config defaults when creating the instance
var instance = axios.create({
baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// Config order of precedence
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
var instance = axios.create();
// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;
// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
timeout: 5000
});
拦截器
// Intercept request/responses
// 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);
});
// Remove interceptor
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
// Custom instance interceptors
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
错误处理
// Catch error
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);
});
// Custom HTTP status code error
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
取消请求
// Cancel request with cancel token
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
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
// Create cancel token
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();
axios API速查表的更多相关文章
- jQuery API 3.1.0 速查表-打印版
jQuery API 3.1.0 速查表-打印图,(API来自:http://jquery.cuishifeng.cn/index.html)
- [翻译]Django速查表
原文在此:https://code.djangoproject.com/wiki/DjangoCheatSheet Django速查表Django教程已经非常好了.这个速查表的作用是创建一个快速开始指 ...
- 这可能是AI、机器学习和大数据领域覆盖最全的一份速查表
https://mp.weixin.qq.com/s?__biz=MjM5ODE1NDYyMA==&mid=2653390110&idx=1&sn=b3e5d6e946b719 ...
- 【译】Swift 字符串速查表
[译]Swift 字符串速查表 2015-12-18 10:32 编辑: suiling 分类:Swift 来源:CocoaChina翻译活动 10 5585 Swift字符串 招聘信息: iOS高级 ...
- 简明 Git 命令速查表(中文版)
原文引用地址:https://github.com/flyhigher139/Git-Cheat-Sheet/blob/master/Git%20Cheat%20Sheet-Zh.md在Github上 ...
- .htaccess下Flags速查表
Flags是可选参数,当有多个标志同时出现时,彼此间以逗号分隔. 速查表: RewirteRule 标记 含义 描述 R Redirect 发出一个HTTP重定向 F Forbidden 禁止对URL ...
- Markdown 语法速查表
Markdown 语法速查表 1 标题与文字格式 标题 # 这是 H1 <一级标题> ## 这是 H2 <二级标题> ###### 这是 H6 <六级标题> 文 ...
- java-Mysql-SQLServer数据类型匹配速查表
java-Mysql-SQLServer数据类型匹配速查表 Mysql ************************************ 当前列 ClassName ColumnType Di ...
- python 下的数据结构与算法---2:大O符号与常用算法和数据结构的复杂度速查表
目录: 一:大O记法 二:各函数高阶比较 三:常用算法和数据结构的复杂度速查表 四:常见的logn是怎么来的 一:大O记法 算法复杂度记法有很多种,其中最常用的就是Big O notation(大O记 ...
随机推荐
- SHU oj 422 风力观测 线段树
风力观测 发布时间: 2017年7月9日 18:17 最后更新: 2017年7月9日 21:04 时间限制: 1000ms 内存限制: 128M 描述 小Y正在观测y地区的风力情况,他在一 ...
- Ubuntu 编译安装 Xdebug
安装xdebug 1.下载 https://xdebug.org/download.php 找到PHP5.6对应的版本 https://xdebug.org/files/xdebug-2.5.5.tg ...
- javaSE习题 第二章 基本数据类型和数组
问答: 1.什么叫标识符,标识符的规则是什么? 用来标志类名,变量名,方法名,类型名,数组名,文件名的有效字符序列称为标识符. 规则:1.由字母,数字,下划线,美元组成.2.标识符第一个字符不能是数字 ...
- JAVA基础知识总结:十五
一.Set接口 Set集合不允许包含相同的元素,如果试图将两个相同的元素添加到一个集合中,使用add方法,添加失败,返回false 1.HashSet HashSet是Set集合的一个实现类,大多数情 ...
- 最简单的解决Chrome浏览器主页被hao123、360和2345篡改的方法是什么
最简单的解决Chrome浏览器主页被hao123.360和2345篡改的方法是什么 一.总结 一句话总结:打开chrome的安装目录,将chrome.exe改成chrome1.exe即可,然后发送一个 ...
- type convert
背景# 在开发中,我们会碰到诸如String类型转换为Int等等问题,虽然处理起来简单,但是本着DRY(Don't Repeat Yourself )原则,还是有必要封装处理下: 具体代码:Maste ...
- python Deep learning 学习笔记
https://www.cnblogs.com/zhhfan/p/10300012.html
- OnSen UI结合AngularJs打造”美团"APP"逛一逛”页面 --Hybrid App
1.页面效果图: 演示链接地址:http://www.nxl123.cn/bokeyuan/meiTuanDemo_walk/ 2.核心代码 walk.html: <ons-page id=&q ...
- 20171104xlVBA各人各科进退
Sub 各班个人各科进步幅度() Dim dRank As Object Set dRank = CreateObject("Scripting.Dictionary") Dim ...
- 20171104xlVBA进退比较
Sub 比对两次成绩() CreateAdvance "进退比较", "月考2", "期中考", "月考2", &quo ...