原来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. P1262 间谍网络

    传送门 思路: ①在 Tarjan 的基础上加一个 belong 记录每个点属于哪个强连通分量. ②存图完成后,暴力地遍历全图,查找是否要间谍不愿受贿. inline void dfs(int u) ...

  2. 下载安装 Android sdk

    下载地址: https://www.androiddevtools.cn/ 选择sdk 选择版本 将解压出的整个文件夹复制或者移动到 your sdk 路径/platforms文件夹,然后打开SDK ...

  3. 使用openpyxl实现excel文件的读取操作

    1.环境准备 python3环境.安装openpyxl模块 2.excel文件数据准备 3.为方便直接调用,本代码直接封装成类 from openpyxl import load_workbook c ...

  4. 事后调试.VC_资料01

    1.windows中的调试_VC语言_编程开发B1_最全面的网站教程.html(http://study.qqcf.com/web/522/98401.htm) windows中的调试 1.事后调试有 ...

  5. Java中的单实例

    前几天刚学完单实例设计模式,今天看代码时发现一行代码很奇怪,getRuntime()函数的返回类型怎么是它本身,忽然想起前几天学的单实例模式,于是找到方法的定义,果然是静态私有变量,获取实例的公有方法 ...

  6. [calss*="col-"]匹配类名中包含col-的类名,^以col-开头,$以col-结尾

    [class*= col-]  代表包含  col-  的类名 , 例 col-md-4 ,demo-col-2(这个是虚构的)等都可以匹配到. [class^=col-]  代表 以 col- 开头 ...

  7. DirectX学习之第一个可运行的工程

    学习一门开发语言的第一件事情当然是搭建一个可运行的环境,然后运行一个可成功执行的案例. 本人在学习DirectX的第一个工程的时候,参考了雨凇MoMo的一篇文章(https://www.xuanyus ...

  8. SublimeText3按ctrl+b执行python无反应

    现象:在Sublime中打开.py文件,按”ctrl+b”执行时无反应.点击工具->编译系统中已经有且识别到Python,但执行”run(ctrl+shift+b)”时无反应,Sublime左下 ...

  9. JFinal3.0 sql管理与动态生成

    原文: 本节学习目标主要是使用JFinal中自带的Template Engin来实现对sql的管理.JFinal中为sql管理提供了3个指令#sql.#para.#namespace,来增强sql功能 ...

  10. 创建.ignore文件

    方法一:1. 在需要创建 .gitignore 文件的文件夹, 右键选择Git Bash 进入命令行,进入项目所在目录.如:(cd /d/git/project) 2. 输入 touch .gitig ...