[web 前端] 封装简单的axios库

转载自https://blog.csdn.net/qq_35844177/article/details/78809499

 

1.新建http.js文件,封装axios get post 方法

import axios from 'axios'
import qs from 'qs'
import 'es6-promise'
 
axios.defaults.baseURL = '/api';
 
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}
 
export function post(url, data) {
  return new Promise((resolve, reject) => {
    axios.post(url, qs.stringify(data), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        }
      }
    ).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

 

2.新建api.js文件,封装调用的接口

import {get, post} from './http'
 
export function getNewPublish() {
  const result = get('/ad/newestPublishAdMaterialInfo1');
  return result;
}

 

3.在组件中使用

import {getNewPublish} from '../../api/api'
 
let result = getNewPublish();
 
result.then(res => {
   console.log(res);
}).catch(err => {
   console.log(err);
})

4.加拦截器的封装

import axios from 'axios'
import qs from 'qs'
import {Toast} from 'antd-mobile'
 
axios.defaults.baseURL = '/api';
 
// 拦截请求
axios.interceptors.request.use(function (config) {
  Toast.loading('加载中', 0);
  return config
});
 
// 拦截相应
axios.interceptors.response.use(function (config) {
  Toast.hide();
  return config
});
 
export default class Http {
  static get(url, params) {
    return new Promise((resolve, reject) => {
      axios.get(url, {
        params: params
      }).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    })
  }
 
  static post(url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, qs.stringify(params), {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          }
        }
      ).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

 

posted @ 2019-08-14 13:53  demoblog  阅读(942)  评论(0编辑  收藏  举报