原来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速查表的更多相关文章

  1. jQuery API 3.1.0 速查表-打印版

    jQuery API 3.1.0 速查表-打印图,(API来自:http://jquery.cuishifeng.cn/index.html)

  2. [翻译]Django速查表

    原文在此:https://code.djangoproject.com/wiki/DjangoCheatSheet Django速查表Django教程已经非常好了.这个速查表的作用是创建一个快速开始指 ...

  3. 这可能是AI、机器学习和大数据领域覆盖最全的一份速查表

    https://mp.weixin.qq.com/s?__biz=MjM5ODE1NDYyMA==&mid=2653390110&idx=1&sn=b3e5d6e946b719 ...

  4. 【译】Swift 字符串速查表

    [译]Swift 字符串速查表 2015-12-18 10:32 编辑: suiling 分类:Swift 来源:CocoaChina翻译活动 10 5585 Swift字符串 招聘信息: iOS高级 ...

  5. 简明 Git 命令速查表(中文版)

    原文引用地址:https://github.com/flyhigher139/Git-Cheat-Sheet/blob/master/Git%20Cheat%20Sheet-Zh.md在Github上 ...

  6. .htaccess下Flags速查表

    Flags是可选参数,当有多个标志同时出现时,彼此间以逗号分隔. 速查表: RewirteRule 标记 含义 描述 R Redirect 发出一个HTTP重定向 F Forbidden 禁止对URL ...

  7. Markdown 语法速查表

      Markdown 语法速查表 1 标题与文字格式 标题 # 这是 H1 <一级标题> ## 这是 H2 <二级标题> ###### 这是 H6 <六级标题> 文 ...

  8. java-Mysql-SQLServer数据类型匹配速查表

    java-Mysql-SQLServer数据类型匹配速查表 Mysql ************************************ 当前列 ClassName ColumnType Di ...

  9. python 下的数据结构与算法---2:大O符号与常用算法和数据结构的复杂度速查表

    目录: 一:大O记法 二:各函数高阶比较 三:常用算法和数据结构的复杂度速查表 四:常见的logn是怎么来的 一:大O记法 算法复杂度记法有很多种,其中最常用的就是Big O notation(大O记 ...

随机推荐

  1. Gson的fromJson()方法把json字符创转为实体

    直接上代码: 1.先看Person实体类 import lombok.Data; @Data public class Person { private String name; private in ...

  2. Redis 图形化监控方案 RedisLive

    一款开源的 Redis 图形化监控工具,界面如图所示 安装 首先安装python2 一般情况下系统自带 然后安装pip2 https://www.cnblogs.com/sea-stream/p/10 ...

  3. gc调优我们到底在调整什么

    java开发一般都会涉及到jvm调优其中gc调优是个重点项.那gc调优调整的究竟是什么呢准确来说是业务.下面围绕这个话题展开 起因 为什么说是业务呢得从cc++开始说起如果说是用c/c++做开发运行的 ...

  4. C#_Demo_摄像头实时_4线程人脸识别注册开发全过程

    v效率有点低,大家看看哪里开可以节省时间?源代码:https://github.com/catzhou2002/ArcFaceDemo说实话,为了提高识别效率,我也是竭尽所能,干了不少自认为的优化,如 ...

  5. HeadFIrst Ruby 第七章总结 hashes

    前言 这一章节介绍了 Ruby 中 hash 这一数据类型的用法和特征. Hash 的定义 与 array 的对比 最大的不同: An array can only use integers as i ...

  6. spring boot ----> spring boot 和spring的联系

    1.自动配置的实现是基于spring 4.0的条件化配置,这是spring 4.0的新特性.比如,定义一个类A,它实现Condition接口,覆盖condition接口的match()方法,那么该类变 ...

  7. English trip V1 - B 4.How Do You Make a Salad? 请给我一间房? Teacher:Julia Key:imperatives 祈使句

    In this lesson you will learn to give instructions. 这节课你将将学会给出指示. 课上内容(Lesson) 词汇(Key Word ) bell pe ...

  8. p1468 Party Lamps

    就是模拟.同一个开关按2下相当于没按,那么,如果一共按0下,就是没按,按1下就是4个开关的1个,按2下可能相当于实际按了0下或按2下,按3下实际按了1下或3下,之后如果是奇数,相当于按1或3下,偶数相 ...

  9. 1. windows 下redis数据库的安装

    安装 window系统的redis是微软团队根据官方的linux版本高仿的 官方原版: https://redis.io/ 中文官网:http://www.redis.cn 下载地址: https:/ ...

  10. MySQL事务(二)

    一.事务的隔离级别/锁问题 基本的介绍: 当我们的mysql表,被多个线程或者客户端同时操作时,mysql提供一种机制,可以让不同的事务在操作数据时,具有隔离性. 锁是计算机协调多个进程或线程并发访问 ...