axios使用说明

为什么转用axios

由于vue的作者尤雨溪大大说了,vue2.0以后的版本已经不再维护vue-resource了,推荐大家使用axios;一番摸索之后,发现axios的使用和ajax极其相似但也有很多不同的地方,于是记下来方面以后回顾

对比ajax和axios的使用方法

在使用axios之前先回顾下如何用jquery的ajax来进行请求:

1
2
3
4
5
6
7
8
9
10
11
12
$.ajax({
type: 'POST', //此处也可以说是GET
url: url,
data: data,
dataType: dataType,
success: function(res, status){
console.log(res);
},
error: function(err){
console.log(err);
}
})

在vue、react等MVVM等框架兴起之前,jquery基本是前端的必备工具,而jquery基于原生XHR的封装的ajax更成为了前后端交互的主要方式,而现在jquery明显有些过时了,下面展示下如何用axios进行数据请求

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
//get请求
axios.get(url, {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

//post请求
axios.post(url, {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//

vue项目里面使用axios使用

安装

1
npm install axios

使用

目前vue里面使用axios大抵是如下两种方式

1、和vue-resource使用类似

在main.js里面引入

1
2
3
4
5
6
7
8
import axios from "axios";

//与很多第三方模块不同的是,axios不能使用use方法,转而应该进行如下操作
Vue.prototype.$axios = axios;
//然后就可以在vue的组件里面使用了
this.$axios.get("/seller",{"id":123}).then(res=>{
console.log(res);
});
2、在需要的模块或者组件里面使用
1
2
3
4
5
6
7
8
9
10
11
12
import axios from 'axios';

axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

如何利用axios来实现跨域

此处以获取QQ音乐的歌词为例,首先打开build文件夹下面的webpack.dev.conf.js

1
2
3
4
5
var express = require('express') //需要npm install express
var axios = require('axios')
var app = express();
var apiRoutes = express.Router();
app.use('/api', apiRoutes)

然后在devWebpackConfig里面的devServer这边写代码如下图:

主要代码就是before里面的这段。
然后在src下面新建一个api文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import axios from 'axios'; //首先引入axios
export function getLyrics(mid) {
const url = '/api/lyric'; //这边是在webpack.dev.conf.js中设置的接口的别名
const param = {
g_tk: 1928093487,
inCharset: 'utf-8',
outCharset: 'utf-8',
notice: 0,
format: 'json',
songmid: mid,
platform: 'yqq',
hostUin: 0,
needNewCode: 0,
categoryId: 10000000,
pcachetime: +new Date()
}; //此处是正常获取数据需要传递的参数
return axios.get(url, {
params:param
}).then((res) => {
return Promise.resolve(res.data);
}) //开始获取数据
}

在想要获取刚刚得到数据的地方引入getLyrics

1
2
3
4
5
import {getLyrics} from 'src/api/lyrics';

getLyrics(mid).then((res) => {
console.log(res);
});

上面这些就是axios的基本使用方法,更多详细信息可以移步这里


axios使用说明
https://xypecho.github.io/2018/05/11/axios使用说明/
作者
很青的青蛙
发布于
2018年5月11日
许可协议