如何用promise封装axios方法

2,569 阅读2分钟

这是我参与11月更文挑战的第12天,活动详情查看:2021最后一次更文挑战

1.axios是什么?

axios:易用、简洁且高效的http库;他基于promise。基于 Promise 的 HTTP 客户端,可以工作于浏览器中,也可以在 node.js 中使用。

2.axios特点?

支持promise:使用Promise管理异步,告别传统callback方式;

支持node端和浏览器端:同样的API,node和浏览器全支持,平台切换无压力;

丰富的配置项:支持拦截器等高级配置;

从浏览器中创建XMLHttpRequests;

3.axios的功能

  • 从浏览器中创建 XMLHttpRequest
  • 从 node.js 中创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防止 XSRF 攻击

4.实例?

(1)执行get请求:

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    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);
  });

(2)执行post请求:

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

(3)执行多个并发请求:

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

上述案例来自axios中文文档:axios中文文档|axios中文网 | axios

5.用promise封装axios?

在实际项目里为了更方便使用axios获取后台数据,在这里进行封装。ue项目里封装方法一般放在utils文件夹里,src下新建一个utils文件夹,index.js文件。

/* eslint-disable no-unused-vars */
import axios from 'axios';


// const get = () => {
//     console.log('get请求');
// }

// const post = () => {
//     console.log('post请求')
// }

// export{
//     get,
//     post
// }

// process.env.NODE_ENV环境
let baseURL;
if(process.env.NODE_ENV=='development'){
    baseURL = 'http://132.232.94.151:3000/api'
}else{
    baseURL = '/xxx'
}
// baseURL es6 方法


const $http = axios.create({
    baseURL,
})
// create 是axios自带的方法

export const get = (url,params)=>{
    params = params || {};
    return new Promise((resolve,reject)=>{
        // axiso 自带 get 和 post 方法
        $http.get(url,{
            params,
        }).then(res=>{
            if(res.data.status===0){
                resolve(res.data);
            }else{
                alert(res.data.msg)
            }
        }).catch(error=>{
            alert('网络异常');
        })
    })
}

export const post = (url,params)=>{
    params = params || {};
    return new Promise((resolve,reject)=>{
        $http.post(url,params).then(res=>{
            if(res.data.status===0){
                resolve(res.data);
            }else{
                alert(res.data.msg);
            }
        }).catch(error=>{
            alert('网络异常');
        })
    })
}

main.js文件中做如下配置:

import { get, post } from "./utils/index";
Vue.prototype.$http = {
  get,
  post
};

(1)上述使用了构造函数的原型prototype(vue属于构造函数);
(2)声明一个全局变量并且把封装好的get和post方法放在里面。

使用封装后的函数:

created() {
    this.getFilmList();
  },
  methods: {
    async getFilmList() {
      const url = "/film/getList";
      // 要访问第二页的话在网址后面加 ?type=2&pageNum=页数
      const res = await this.$http.get(url);
      this.filmList = res.films;
    },

注意:因为是promise封装的函数方法,所以使用的时候要加上async 函数(){ await 数据} 不然会报错,因为没有完成异步转同步。