英文原文链接

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 defaultsaxios.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 sentreturn config;}, function (error) {// Do something with request errorreturn Promise.reject(error);});// Add a response interceptor
axios.interceptors.response.use(function (response) {// Do something with response datareturn response;}, function (error) {// Do something with response errorreturn Promise.reject(error);});// Remove interceptorvar myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);// Custom instance interceptorsvar instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

错误处理

// Catch erroraxios.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 2xxconsole.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.jsconsole.log(error.request);} else {// Something happened in setting up the request that triggered an Errorconsole.log('Error', error.message);}console.log(error.config);});// Custom HTTP status code erroraxios.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 tokenvar 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 tokenvar CancelToken = axios.CancelToken;
var cancel;axios.get('/user/12345', {cancelToken: new CancelToken(function executor(c) {// An executor function receives a cancel function as a parametercancel = c;})
});// cancel the request
cancel();

我想知道掘金的读者是不是只收藏不看文章。看到这句话回复1

Axios 作弊表(Cheat Sheet)相关推荐

  1. 机器学习相关速查表Cheat Sheet

    写在前面 早上逛技术新闻时,看到的一个有意思的帖子,分享给大家:) 速查表内容包括(12项): keras numpy pandas scipy matplotlib scikit-learn neu ...

  2. mysql 递归_「MySQL」 - SQL Cheat Sheet - 未完成

    近几个月的心情真是安排的妥妥的,呈现W状.多的不说了,这里对SQL的测试进行简单梳理,制作一份SQL Cheat Sheet. 0x01.数据库基本架构 Clinet层 Server层 连接器 网络连 ...

  3. ubuntu cheat sheet 目录结构

     Ubuntu Cheat Sheet Ubuntu系统目录结构 以下为Ubuntu目录的主要目录结构,您稍微了解它们都包含了哪些文件就可以了,不需要记忆. / 根目录 │ ├boot/ 启动文件.所 ...

  4. 容器编排技术 -- kubectl Cheat Sheet

    容器编排技术 -- kubectl Cheat Sheet 1 Kubectl 自动补全 2 Kubectl 上下文和配置 3 创建对象 4 显示和查找资源 5 更新资源 6 修补资源 7 编辑资源 ...

  5. Markdown Cheat Sheet

    目录 Markdown Cheat Sheet 数学相关LaTeX表达 前言 表 1: 数学模式重音符 表2: 小写希腊字母 表 3: 大写希腊字母 表 4: 数学字母 表 5: 运算符与函数 表 6 ...

  6. Cheat Sheet的意思

    刚才查了下:Cheat  Sheet的意思是备忘录. cheat是作弊的意思.这个词组原来的意思应该是考试作弊用的小抄吧.

  7. CCF-CSP Python Cheat Sheet

    这里写自定义目录标题 Python Cheat Sheet string 字符串的运算 格式化输出 三引号 其他 List Dictionary Set Graph 邻接表形式 DFS BFS 杂项 ...

  8. 139.00.007 Git学习-Cheat Sheet

    @(139 - Environment Settings | 环境配置) Git虽然极其强大,命令繁多,但常用的就那么十来个,掌握好这十几个常用命令,你已经可以得心应手地使用Git了. 友情附赠国外网 ...

  9. Emmet Cheat Sheet(Sublime编辑)

    快捷创建html标签 官网的Emmet Cheat Sheet :http://docs.emmet.io/cheat-sheet/ https://files.cnblogs.com/files/t ...

最新文章

  1. 利用Event和MapFile进程共享信息
  2. Silverlight+WCF 新手实例 象棋 主界面-实时聊天区(二十五)
  3. pandas读取csv Error tokenizing data. C error: Expected 18 fields in line 173315, saw 20
  4. 携程是如何把大数据用于实时风控的
  5. 深度学习目标检测(YoloV5)项目——从0开始到项目落地部署
  6. 买卖股票的最佳时机II
  7. MyBatis collection的两种形式——MyBatis学习笔记之九
  8. 2017杭电ACM集训队单人排位赛 - 1(ALL题解)
  9. 中国象棋-单机游戏-微信小程序的项目开发流程详解
  10. 俄亥俄州立大学计算机硕士申请,俄亥俄州立大学计算机科学与工程理学硕士研究生申请要求及申请材料要求清单...
  11. 爬取武汉大学教务系统数据
  12. ESP8266-NodeMCU项目(四):将上一项目的空调控制接入小爱同学(Blinker_APP同步控制+DHT11温湿度模块数据接入)
  13. 微信小程序九宫格预览+单张图片预览
  14. ValueError: Cannot have number of splits n_splits=10 greater than the number of samples: n_samples=0
  15. GX works2 三菱PLC 显示注释后代码行变宽的解决方法
  16. Java简易图书DVD管理系统
  17. 京东区块链之科普篇:京东在区块链技术领域的应用与布局
  18. 基于c语言的象棋游戏
  19. C语言 - 巧解正数,负数以及零的按位取反
  20. 荣耀YOYO建议新增快递取件服务

热门文章

  1. 解决Tomcat8及Tomcat7下http的post、get请求中参数中文乱码问题
  2. toString()方法使用
  3. 用matlab做纹理合成,关于图像纹理合成的Matlab例程
  4. NOIP模拟测试26「嚎叫响彻在贪婪的机房·主仆见证了 Hobo 的离别·征途堆积出友情的永恒」...
  5. Codeforces Round #344 (Div. 2) B. Print Check
  6. Netty writeAndFlush() 流程与异步
  7. ref 和out 关键字
  8. Python多篇新闻自动采集
  9. php static方法的作用是什么,php static方法指的是什么
  10. tf.layers.flatten