Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

一个最大的疑问:为什么不用jquery?

jquery是封装dom,vue是数据驱动dom;jquery封装ajax,axios是基于promise。

在vue项目中引入axios

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div id="app"></div>
<script src="./node_modules/vue/dist/vue.min.js"></script>
<script src="./node_modules/axios/dist/axios.min.js"></script>
<script>
const App = {
template: '<div></div>'
}
Vue.prototype.$axios = axios;
new Vue({
el: '#app',
data() {
return {

}
},
components: {
App
},
template: '<App />'
})
</script>

koa搭建node服务器

在演示真实请求之前,我们先用koa搭建一个简单的node服务器,因不在本次讲解之内,直接先贴代码,我们实际关注的就是后台给到的一些接口。在server目录下:

1
npm i koa koa-router -S
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
// server.js
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();

app.use(async(ctx, next) => {
ctx.response.set('Access-Control-Allow-Origin', '*');
ctx.response.set("Access-Control-Allow-Headers", 'content-type');
await next();
});

app.use(router.routes());
app.use(router.allowedMethods());

router.get('/', async ctx => {
ctx.body = {
code: 200,
msg: 'get ok!'
};
})
.post('/add', async ctx => {
ctx.req.on('data', data => {
console.log(data.toString());
});
ctx.body = {
code: 200,
msg: 'post ok!'
};
})

app.listen(8888, () => {
console.log('Server is running !')
})

启动服务

1
node server.js

发送get请求和post请求

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
const App = {
template: `<div>
<button @click="sendGetRequest">发送get请求</button>
<button @click="sendPostRequest">发送post请求</button>
</div>`,

methods: {
sendGetRequest() {
this.$axios.get('http://127.0.0.1:8888/')
.then(res => {
console.log(res.data)
})
.catch(err => {
console.log(err)
})
},
sendPosRequest() {
this.$axios.post('http://127.0.0.1:8888/add', {
username: 'jerry',
password: '123'
}).then(res => {
console.log(res.data)
}).catch(err => {
console.log(err)
})
}
}
}

并发请求

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
Vue.prototype.$axios.defaults.baseURL = 'http://127.0.0.1:8888';
const App = {
template: `
<div>
<button @click="sendMultiRequest">发送并发请求</button>
</div>
`,

methods: {
sendMultiRequest() {
let req1 = this.$axios.get('/');
let req2 = this.$axios.post('/add', {
username: 'jerry',
password: '123'
});
this.$axios.all([req1, req2])
.then(this.$axios.spread((res1, res2) => {
console.log(res1.data)
console.log(res2.data)
}))
.catch(err => {
console.log(err)
})
}
}
}

请求配置

自定义配置创建axios实例

1
2
3
4
5
const instance = axios.create({
baseURL: 'http://127.0.0.1:8888',
timeout: 4000
})
Vue.prototype.$axios = instance;

转换响应数据transformResponse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const App = {
template: `
<div>
<button @click="sendPostRequest">发送post请求</button>
</div>
`,

methods: {
sendPostRequest() {
this.$axios.post('/add', 'name=jerry', {
transformRequest: [function(data) {
console.log('请求之前', data)
data = 'name=tom'
console.log('请求之后', data)
return data;
}]
})
.then((res) => {
console.log(res.data)
}).catch(err => {
console.log(err)
})
}
}
}

转换请求数据transformRequest

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
const App = {
template: `
<div>
<button @click="sendGetRequest">发送get请求</button>
</div>
`,

methods: {
sendGetRequest() {
this.$axios.get('/', {
params: {
id: 1
},
transformResponse: [function(data) {
console.log('响应之前', data)
data = JSON.parse(data);
return data;
}]
})
.then(res => {
console.log('实际响应', res.data)
})
.catch(err => {
console.log(err)
})
}
}
}

拦截器

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
const App = {
data() {
return {
isShow: false
}
},
template: `
<div>
<div v-show="isShow">加载中。。。。</div>
<button @click="sendGetRequest">发送get请求</button>
</div>
`,

methods: {
sendGetRequest() {
// 添加请求拦截器
this.$axios.interceptors.request.use(config => {
// 发送请求之前做点什么
console.log(config)
this.isShow = true;
alert('发送请求之前做点什么')
return config;
})
this.$axios.interceptors.response.use(res => {
// 响应数据做点什么
alert('响应数据之前做点什么')
this.isShow = false;
return res;
})
this.$axios.get('http://127.0.0.1:8888/')
.then(res => {
console.log(res.data)
})
.catch(err => {
console.log(err)
})
}
}
}

取消请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/login', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 处理错误
}
});

// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');