vue.js 自2.0版本已经不对 vue-resource 更新了,官方推荐使用 axios 解决方案。axios 使用了 Promise,而 jquery 自3.0 版本才支持 Promise,如果你只是想使用 jquery 的 ajax 的话,引入整个 jquery 是很大的负担,所以 axios 是一个很好的工具。
知识点:
1.webpack
2.ES6
3.babel
4.node npm
5.eslint
6.axios
7.DOS基本命令
注意:需要使用 node环境,请先安装node,并学习 npm 的使用方法。
为了熟练操作,该文章中会使用一些DOS命令,很多人觉得window比linux方便,但是当你用习惯了linux命令的话,操作确实比window方便很多。
开始
创建项目目录
打开 DOS,切换到一个目录下,使用:
md axiosTest
建立空文件夹, 然后使用模糊匹配切换到创建的目录:
cd axios*
使用 npm init 创建 package.json 文件:

项目文件
创建 webpack.config.js 文件:
webpack.config.js
:
module.exports = {
entry: {
page1: './main'
},
output: {
path: __dirname + '/build',
filename: '[name].bundle.js'
},
module: {
loaders:[
{
test: /\.js$/,
loaders: ['babel-loader', 'eslint-loader'],
exclude: '/node_modules' /*排除该文件夹*/
}
]
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
同目录下建立 main.js
:
import app from './app';
同目录建立 app.js
:
import axios from 'axios';
//请求前拦截
axios.interceptors.request.use((config) => {
console.log("请求前拦截!");
return config;
}, (err) => {
return Promise.reject(err);
});
//发送一个 get 请求
axios.get('package.json')
.then( (res) => {
console.log(res);
})
.catch( (err) => {
console.log(err);
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
同目录建立 index.html
:
<html>
<head>
<title>axios</title>
<meta name="charset" content="utf8">
<script type="text/javascript" src="./build/page1.bundle.js"></script>
</head>
<body>
</body>
</html>
因为使用了 eslint, 所以编写 配置文件,同目录建立 .eslintrc
:
{
"parser": 'babel-eslint',
"rules": {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// http://eslint.org/docs/rules/comma-dangle
'comma-dangle': ['error', 'only-multiline'],
'semi': 0,
'eol-last': 2
}
}
安装必要模块
使用 npm install --save-dev XXX
安装以下模块:
- webpack
- webpack-dev-server
- babel-core
- babel-esling
- babel-loader
- babel-preset-es2015
- babel-preset-stage-2
- eslint
- eslint-loader
-
axios
可以看到我们的 package.json 中已经有了安装的模块,继续在 scripts
中添加我们的编译和启动静态服务器的命令:
package.json
:
{
"name": "axios_test",
"version": "1.0.0",
"description": "axios test",
"main": "index.js",
"scripts": {
"server": "webpack --progress --colors && webpack-dev-server --hot --watch --port 8086"
},
"keywords": [
"axios"
],
"author": "zhao",
"license": "MIT",
"devDependencies": {
"axios": "^0.16.1",
"babel-core": "^6.24.1",
"babel-eslint": "^7.2.2",
"babel-loader": "^6.4.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"eslint": "^3.19.0",
"eslint-loader": "^1.7.1",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.2"
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
运行
在 DOS 中对应工程目录下输入:
npm run server
项目开始编译及启动服务器:

在浏览器输入:
http://localhost:8086/
可以看到运行结果:

好了,上述只是用 综合的知识搭建了一个基本框架,下面详细讲述 axios 的内容。
原文
axios
基于http客户端的promise,面向浏览器和nodejs
特色
- 浏览器端发起XMLHttpRequests请求
- node端发起http请求
- 支持Promise API
- 监听请求和返回
- 转化请求和返回
- 取消请求
- 自动转化json数据
- 客户端支持抵御
可以看到比 jquery 的 ajax 强多了!
示例
get 请求:
axios.get('/user?ID=1234')
.then(function(respone){
console.log(response);
})
.catch(function(error){
console.log(error);
});
axios.get('/user',{
params:{
ID:12345
}
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error)
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
post 请求:
axios.post('/user',{
firstName:'friend',
lastName:'Flintstone'
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
多重并发请求:
function getUserAccount(){
return axios.get('/user/12345');
}
function getUserPermissions(){
return axios.get('/user/12345/permissions');
}
axios.all([getUerAccount(),getUserPermissions()])
.then(axios.spread(function(acc,pers){
}));
axios API
axios(config)
axios({
method:'post',
url:'/user/12345',
data:{
firstName:'Fred',
lastName:'Flintstone'
}
});
axios(url[,config])
axios('/user/12345/);
为了方便,axios提供了所有请求方法的重命名支持
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]])
注意
当时用重命名方法时 url , method ,以及 data 特性不需要在config中设置。
并发 Concurrency
有用的方法
axios.all(iterable)
axios.spread(callback)
创建一个实例
你可以使用自定义设置创建一个新的实例
axios.create([config])
var instance = axios.create({
baseURL:'http://some-domain.com/api/',
timeout:1000,
headers:{'X-Custom-Header':'foobar'}
});
实例方法
下面列出了一些实例方法。具体的设置将在实例设置中被合并。
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]])
请求设置
以下列出了一些请求时的设置。只有 url 是必须的,如果没有指明的话,默认的请求方法是 GET .
{
url:'/user',
method:`get`,
baseURL:'http://some-domain.com/api/',
transformRequest:[function(data){
return data;
}],
transformResponse:[function(data){
return data;
}],
headers:{'X-Requested-with':'XMLHttpRequest'},
params:{
ID:12345
},
paramsSerializer: function(params){
return Qs.stringify(params,{arrayFormat:'brackets'})
},
data:{
firstName:'fred'
},
timeout:1000,
withCredentials:false
adapter:function(config){
},
auth:{
username:'janedoe',
password:'s00pers3cret'
},
responsetype:'json',
xrsfHeadername:'X-XSRF-TOKEN',
onUploadProgress: function(progressEvent){
},
onDownloadProgress: function(progressEvent){
},
maxContentLength: 2000,
validateStatus: function(status){
return status >= 200 && stauts < 300;
},
httpAgent: new http.Agent({keepAlive:treu}),
httpsAgent: new https.Agent({keepAlive:true}),
proxy:{
host:127.0.0.1,
port:9000,
auth:{
username:'cdd',
password:'123456'
}
},
cancelToke: new CancelToken(function(cancel){
})
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
返回响应概要 Response Schema
一个请求的返回包含以下信息
{
//`data`是服务器的提供的回复(相对于请求)
data{},
//`status`是服务器返回的http状态码
status:200,
//`statusText`是服务器返回的http状态信息
statusText: 'ok',
//`headers`是服务器返回中携带的headers
headers:{},
//`config`是对axios进行的设置,目的是为了请求(request)
config:{}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
使用 then ,你会得到下面的信息
axios.get(
.then(function(response){
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
使用 catch 时,或者传入一个 reject callback 作为 then 的第二个参数,那么返回的错误信息将能够被使用。
默认设置(Config Default)
你可以设置一个默认的设置,这设置将在所有的请求中有效。
全局默认设置 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 default
var instance = axios.create({
baseURL:'https://api.example.com'
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
设置优先级 Config order of precedence
设置(config)将按照优先顺序整合起来。首先的是在 lib/defaults.js 中定义的默认设置,其次是 defaults 实例属性的设置,最后是请求中 config 参数的设置。越往后面的等级越高,会覆盖前面的设置。
看下面这个例子:
var instance = axios.create();
instance.defaults.timeout = 2500;
instance.get('/longRequest',{
timeout:5000
});
拦截器 interceptors
你可以在 请求 或者 返回 被 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);
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
如果你需要在稍后移除拦截器,你可以:
var myInterceptor = axios.interceptors.request.use(function(){/*...*/});
axios.interceptors.rquest.eject(myInterceptor);
你可以在一个axios实例中使用拦截器
var instance = axios.create();
instance.interceptors.request.use(function(){/*...*/});
错误处理 Handling Errors
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);
});
你可以使用 validateStatus 设置选项自定义HTTP状态码的错误范围。
axios.get('user/12345',{
validateStatus:function(status){
return status < 500;
}
});
取消 Cancellation
你可以使用 cancel token 取消一个请求
axios的cancel token API是基于cnacelable promises proposal,其目前处于第一阶段。
你可以使用 CancelToke.source 工厂函数创建一个cancel token,如下:
var CancelToke = axios.CancelToken;
var source = CancelToken.source();
axios.get('/user/12345', {
cancelToken:source.toke
}).catch(function(thrown){
if(axiso.isCancel(thrown)){
console.log('Rquest canceled', thrown.message);
}else{
}
});
source.cancel("操作被用户取消");
你可以给 CancelToken 构造函数传递一个executor function来创建一个cancel token:
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c){
cancel = c;
})
});
cancel();
注意:你可以使用同一个cancel token取消多个请求。
使用 application/x-www-form-urlencoded 格式化
默认情况下,axios串联js对象为 JSON 格式。为了发送 application/x-wwww-form-urlencoded 格式数据,
你可以使用一下的设置。
浏览器 Browser
在浏览器中你可以如下使用 URLSearchParams API:
var params = new URLSearchParams();
params.append('param1','value1');
params.append('param2','value2');
axios.post('/foo',params);
注意: URLSearchParams 不支持所有的浏览器,但是这里有个 垫片
(poly fill)可用(确保垫片在浏览器全局环境中)
其他方法:你可以使用 qs 库来格式化数据。
var qs = require('qs');
axios.post('/foo', qs.stringify({'bar':123}));
Node.js
在nodejs中,你可以如下使用 querystring :
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({foo:'bar'}));
你同样可以使用 qs 库。
promises
axios 基于原生的ES6 Promise 实现。如果环境不支持请使用 垫片 .