1. 安装axios

在项目下执行npm install axios。

之后在main.js中,添加:

1

2

3

4


import axios from 'axios' //引入

 

//Vue.use(axios) axios不能用use 只能修改原型链

Vue.prototype.$axios = axios


2. 发送GET请求

axios封装了get方法,传入请求地址和请求参数,就可以了,同样支持Promise。

1

2

3

4

5

6

7

8

9

10


//不带参数的get请求

 

let url = "..."

this.$axios.get(url)

.then((res) => {

console.log(res) //返回的数据

})

.catch((err) => {

console.log(err) //错误信息

})


不过它的参数需要写在params属性下,也就是:

1

2

3

4

5

6

7

8

9

10

11

12

13

14


//带参数的get请求

 

let url = "...getById"

this.$axios.get(url, {

params: {

id: 1

}

})

.then((res) => {

console.log(res) //返回的数据

})

.catch((err) => {

console.log(err) //错误信息

})


2. 发送post请求

与上面相同,就是参数不需要写在params属性下了,即:

1

2

3

4

5

6

7

8

9

10

11

12

13

14


//带参数的post请求

 

let url = "...getById"

let data = {

id: 1

}

 

this.$axios.post(url, data)

.then((res) => {

console.log(res) //返回的数据

})

.catch((err) => {

console.log(err) //错误信息

})


3. 经典写法

axios也可以用jQ的写法,不过回调函数还是Promise的写法,如:

1

2

3

4

5

6

7

8

9

10


this.$axios({

method: 'post',

url: '...',

data: {

firstName: 'Fred',

lastName: 'Flintstone'

}

}).then((res) => {

console.log(res)

})


设置form-data请求格式

我用默认的post方法发送数据的时候发现后端获取不到数据,然而在network中看到参数是的确传出去的了。而且用postman测试的时候也是可以的,比较了下两个的不同发现是postman使用的是form-data格式,于是用form-data格式再次请求,发现OJBK

在查找设置请求格式的时候花了点时间,网上的方案有好几个,这个我亲测成功,发上来。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16


import axios from "axios" //引入

 

//设置axios为form-data

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';

axios.defaults.transformRequest = [function (data) {

let ret = ''

for (let it in data) {

ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'

}

return ret

}]

 

 

//然后再修改原型链

Vue.prototype.$axios = axios