原来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. XMind 8 Update 7 Pro 激活码

    XMind Update Pro 邮箱:x@iroader 序列号: XAka34A2rVRYJ4XBIU35UZMUEEF64CMMIYZCK2FZZUQNODEKUHGJLFMSLIQMQUCUB ...

  2. JDBC连接数据库的简单介绍

    休息10天后重新看了下jdbc,开始振作继续学习(休息10天主要是因为驾照考试太累,2333),希望自己能够调整好心态,继续对程序有着一如既往的喜爱(加油) Connection con=null; ...

  3. N的阶乘(10000) 51 nod——1057 (大数)

    像这些大整数加法或者乘法什么的思想都一样,就是截位存取,累积进位,最后逆序输出就可以啦 PS:小生是用10000来存取的,300MS就能A,如果单个存取有点危险,题目时间限制好像是1000ms,大家可 ...

  4. Qt532.数值转为16进制(并填充)

    ZC:QString::number(要转换的数值, 需要转换的目标进制); ZC:QString("%1").arg(要转换的数值, 需要填充到?位, 需要转换的目标进制, 用于 ...

  5. [原][粒子特效][spark]插值器interpolator

    深入浅出spark粒子特效连接:https://www.cnblogs.com/lyggqm/p/9956344.html 插值器是体现粒子生命周期变化的功能 group使用到插值器的方式: 可以看到 ...

  6. nRF52832定时器

    1概述 定时器能够被配置为两种模式:定时模式和计数模式,nrf52832有五个定时器,timer0--timer4 . 2常用得函数 函数功能:初始化定时器 ret_code_t nrf_drv_ti ...

  7. Anaconda 简单介绍 -- 环境管理

    前面介绍了 Anaconda 的安装,接下来介绍一下 简单使用,后续并实时更新. 常用操作命令: 环境操作 1.查看环境管理的全部命令帮助: conda env -h 2.查看当前系统下的环境: co ...

  8. Angular 学习笔记 ( timezone + moment + material date-picker + date pipe + asp.net core )

    参考 : https://stackoverflow.com/questions/29979609/time-conversion-with-timezoneinfo-for-past-years h ...

  9. python中函数与函数式编程(一)

    在学习之前,我们先去区分面对对象.面对过程.函数式编程他们之间的区别,从改图可以看出,他们之间不是完全相同的,也不是没有任何相同点的 1.函数和过程的基本认识 def func1(): "& ...

  10. 池建强 Mac Tips

    摘自<MacTalk 人生元编程>,原文有130条,从中摘录出7条:大部分与  Terminal 相关 1. 终端说英语 在终端输入 " say hello" ,Mac ...