Axios
Axios是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。axios主要是用于向后台发起请求的,还有在请求中做更多可控功能。官方不再维护vue-resource,推荐使用axios。
axios:https://www.kancloud.cn/yunye/axios/234845
1.Axios引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
npm install axios --save
2.基础API
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
3.Get请求
1 | axios.get('/user', { |
2 | params: { |
3 | ID: 12345 |
4 | } |
5 | }) |
6 | .then(function (response) { |
7 | console.log(response); |
8 | }) |
9 | .catch(function (error) { |
10 | console.log(error); |
11 | }); |
4.Post请求
1 | axios.post('/user', { |
2 | ID: 12345 |
3 | }) |
4 | .then(function (response) { |
5 | console.log(response); |
6 | }) |
7 | .catch(function (error) { |
8 | console.log(error); |
9 | }); |
5.Http请求
1 | axios({ |
2 | url:"/user", |
3 | method:"get",//"post" |
4 | data:{userId:"101"},//Post |
5 | params:{userId:"101"},//Get |
6 | headers:{token:"http-test"} |
7 | }).then(res=>{this.msg=res.data;}) |
6.多个并发请求
1 | function getUserAccount() { |
2 | return axios.get('/user/12345'); |
3 | } |
4 | |
5 | function getUserPermissions() { |
6 | return axios.get('/user/12345/permissions'); |
7 | } |
8 | |
9 | axios.all([getUserAccount(), getUserPermissions()]) |
10 | .then(axios.spread(function (acct, perms) { |
11 | // 两个请求现在都执行完成 |
12 | })); |
7.全局拦截器
1 | // 添加请求拦截器 |
2 | axios.interceptors.request.use(function (config) { |
3 | // 在发送请求之前做些什么 |
4 | return config; |
5 | }, function (error) { |
6 | // 对请求错误做些什么 |
7 | return Promise.reject(error); |
8 | }); |
9 | |
10 | // 添加响应拦截器 |
11 | axios.interceptors.response.use(function (response) { |
12 | // 对响应数据做点什么 |
13 | return response; |
14 | }, function (error) { |
15 | // 对响应错误做点什么 |
16 | return Promise.reject(error); |
17 | }); |