axios的基本使用

vue更新到2.0之后,作者就宣告不再对vue-resource更新,而是推荐的 axios

基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用

版本 v0.15.3

功能特性

  • 在浏览器中发送 XMLHttpRequests 请求
  • 在 node.js 中发送 http请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 自动转换 JSON 数据
  • 客户端支持保护安全免受 XSRF 攻击

请求方式

axios(config)
 
axios.request(config)
 
axios.get(url[, config])
 
axios.delete(url[, config])
 
axios.head(url[, config])
 
axios.post(url[, data[, config]])
 
axios.put(url[, data[, config]])
 
axios.patch(url[, data[, config]])

get请求

axios
.get('/user',{ params:{id: 12} })
.then(res=>{ console.log(res) })
.catch(err=>{ console.log(err) })

post请求

axios
.post('/user',{id: 12})
.then(res=>{ console.log(res) })
.catch(err=>{ console.log(err) })

发送并发请求

axios
.all([axios.get('/profile'), axios.post('/user')])
.then(axios.spread((res1, res2)=>{
console.log(res1)
console.log(res2)
}))

axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2

直接通过配置发送请求,类似于 $.ajax(config)

axios(config) / axios(url,[config])

axios({
url:'/user',
method: 'post',
data:{ id: 1 },
})
 
axios('/user/12')

axios实例

实例配置

使用自定义的配置创建一个axios实例

var axiosIns = axios.create({
baseURL: '',
timeout: 60000,
headers: {'X-Custom-Header': 'foo'}
})

axiosIns.get/post/delete/put/patch/head 都可以共用实例配置

请求配置

{
// 请求地址
url: '/user',
// 请求类型
method: 'get',
// 请根路径
baseURL: 'http://www.mt.com/api',
// 请求前的数据处理
transformRequest:[function(data){}],
// 请求后的数据处理
transformResponse: [function(data){}],
// 自定义的请求头
headers:{'x-Requested-With':'XMLHttpRequest'},
// URL查询对象
params:{ id: 12 },
// 查询对象序列化函数
paramsSerializer: function(params){ }
// request body
data: { key: 'aa'},
// 超时设置s
timeout: 1000,
// 跨域是否带Token
withCredentials: false,
// 自定义请求处理
adapter: function(resolve, reject, config){},
// 身份验证信息
auth: { uname: '', pwd: '12'},
// 响应的数据格式 json / blob /document /arraybuffer / text / stream
responseType: 'json',
 
// xsrf 设置
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
 
// 下传和下载进度回调
onUploadProgress: function(progressEvent){
Math.round( (progressEvent.loaded * 100) / progressEvent.total )
},
onDownloadProgress: function(progressEvent){},
 
// 最多转发数,用于node.js
maxRedirects: 5,
 
// 最大响应数据大小
maxContentLength: 2000,
// 自定义错误状态码范围
validateStatus: function(status){
return status >= 200 && status < 300;
},
// 用于node.js
httpAgent: new http.Agent({ keepAlive: treu }),
httpsAgent: new https.Agent({ keepAlive: true }),
 
// 用于设置跨域请求代理
proxy: {
host: '127.0.0.1',
port: 8080,
auth: {
username: 'aa',
password: '2123'
}
},
// 用于取消请求
cancelToken: new CancelToken(function(cancel){})
}

响应的数据结构

{
data: {}, //服务器返回的数据
status: 200,
statusText: 'OK',
headers: {},
config: {}
}

全局配置

应用于所有请求

axios.defaults.baseURL = ‘http://www.mt.com/api
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;

拦截请求与响应

在 then 或 catch 之前拦截处理

// 请求拦截
axios.interceptors.request.use(function (config) {
// 处理请求之前的配置
return config;
}, function (error) {
// 请求失败的处理
return Promise.reject(error);
});
 
// 响应拦截
axios.interceptors.response.use(function (response) {
// 处理响应数据
return response;
}, function (error) {
// 处理响应失败
return Promise.reject(error);
});

错误处理

axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// 服务器返回正常的异常对象
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
// 服务器发生未处理的异常
console.log('Error', error.message);
}
console.log(error.config);
});

取消请求

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
}
});
 
// 取消请求
source.cancel('Operation canceled by the user.');
var CancelToken = axios.CancelToken;
var cancel;
 
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
});
 
// 取消请求
cancel();

qs模块

用于处理URL查询参数

var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

【转】axios的基本使用的更多相关文章

  1. 为什么axios请求接口会发起两次请求

    之前在使用axios发现每次调用接口都会有两个请求,第一个请求时option请求,而且看不到请求参数,当时也没注意,只当做是做了一次预请求,判断接口是否通畅,但是最近发现并不是那么回事. 首先我们知道 ...

  2. axios基本用法

    vue更新到2.0之后,作者就宣告不再对vue-resource更新,而是推荐的axios,前一段时间用了一下,现在说一下它的基本用法. 首先就是引入axios,如果你使用es6,只需要安装axios ...

  3. Axios、Lodash、TweenJS

    Axios是一个基于promise的HTTP库 http://chuansong.me/n/394228451820 Lodash是一个JavaScript的函数工具集 http://www.css8 ...

  4. axios全攻略

    随着 vuejs 作者尤雨溪发布消息,不再继续维护vue-resource,并推荐大家使用 axios 开始,axios 被越来越多的人所了解.本来想在网上找找详细攻略,突然发现,axios 的官方文 ...

  5. 抛弃vue-resource拥抱axios

    vue-resource用法 import Vue from 'vue' import VueResource from 'vue-resource' Vue.use(VueResource) 是不是 ...

  6. Vue+axios 实现http拦截及路由拦截

    现如今,每个前端对于Vue都不会陌生,Vue框架是如今最流行的前端框架之一,其势头直追react.最近我用vue做了一个项目,下面便是我从中取得的一点收获. 基于现在用vue+webpack搭建项目的 ...

  7. vue使用Axios做ajax请求

    vue2.0之后,就不再对vue-resource更新,而是推荐使用axios 1. 安装 axios $ npm install axios 或 $ bower install axios 2. 在 ...

  8. vue全家桶(Vue+Vue-router+Vuex+axios)(Vue+webpack项目实战系列之二)

    Vue有多优秀搭配全家桶做项目有多好之类的咱就不谈了,直奔主题. 一.Vue 系列一已经用vue-cli搭建了Vue项目,此处就不赘述了. 二.Vue-router Vue的路由,先献上文档(http ...

  9. 9.如何解决出现AXIOS的Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

    问题描述: 由于restful接口需要在头部header传递两个字段: Content-Type: application/jsonAccess-Token: 84c6635800b14e0eba4f ...

  10. vue2.0设置proxyTable使用axios进行跨域请求

    这里请求的是知乎日报的api,由@izzyleung这位大神提供的,这是github地址. 在vue-cli构建的项目中先安装axios npm install axios -S 这里暂不考虑用vue ...

随机推荐

  1. 关于Runtime Issues

    前言:在使用某移动直播的SDK的时候发现,在Run应用的时候会有紫色的警告(Xcode9 + iOS11) 当时还专门提交了工单,当时对方的回复是,大概意思是不影响使用,后期修复. 今天看视频发现这是 ...

  2. XAMPP安装过程中,出现的问题

    这次运行一个简单的前端(html+css+js+ajax)+php后端项目,运行XAMPP的时候,出现两个问题: phpmyadmin运行不起来,一直报1544错误 请求本地图片及php文件报403错 ...

  3. package.json字段分析

    分析1.必须在包的顶层目录下2.二进制文件应该在bin目录下3.javascipt在lib目录下4.文档在doc目录下 package.json字段分析 name:包的名称,必须是唯一的,由小写英文字 ...

  4. 【css】如何实现响应式布局

    “自适应网页设计”到底是怎么做到的?其实并不难. 首先,在网页代码的头部,加入一行viewport元标签. <meta name="viewport" content=&qu ...

  5. Python入门基础--变量与基本数据类型

    变量 什么是变量 变量就是变化的量,变就是变化,量用于衡量描述对象的状态 为什么要有变量 程序执行的本质就是一系列状态的变化,变是程序执行的直接体现,所以我们需要有一种机制能够反映或者说是保存下来程序 ...

  6. python学习——StringIO和BytesIO

    StringIO 很多时候,数据读写不一定是文件,也可以在内存中读写. StringIO顾名思义就是在内存中读写str. 要把str写入StringIO,我们需要先创建一个StringIO,然后,像文 ...

  7. Ralph W. Tyler【拉尔夫·泰勒】

    Ralph W. Tyler Anyone who cares about what schools and colleges teach and how their student learn wi ...

  8. Kilani and the Game CodeForces - 1105D (bfs)

    Kilani is playing a game with his friends. This game can be represented as a grid of size n×mn×m, wh ...

  9. Terrorist’s destroy HDU - 4679

    Terrorist’s destroy HDU - 4679 There is a city which is built like a tree.A terrorist wants to destr ...

  10. 51NOD:1639-绑鞋带

    传送门:https://www.51nod.com/onlineJudge/submitDetail.html#!judgeId=475129 1639 绑鞋带 基准时间限制:1 秒 空间限制:131 ...