axios的简易封装

繁琐的http请求多而复杂,这里就将axios的get和post进行封装,以方便后续在项目中方便的使用。

首先创建一个名为http.js的js然后下面就是http.js中的代码:

http.js

import axios from 'axios'
import qs from 'qs'
let localhosts = '这里是要请求的url';
axios.interceptors.request.use(config => {
  // loading
  return config
}, error => {
  return Promise.reject(error)
});

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
});
function checkStatus(response) {
  // loading
  // 如果http状态码正常,则直接返回数据
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    return response
    // 如果不需要除了data之外的数据,可以直接 return response.data
  }
  // 异常状态下,把错误信息返回去
  return {
    status: 404,
    msg: '网络异常'
  }
}

function checkCode(res) {
  // 如果code异常(这里已经包括网络错误,服务器错误,后端抛出的错误),可以弹出一个错误提示,告诉用户
  if (res.status === 404) {
    // alert(res.msg)
  }
  if (res.data && (!res.data.success)) {
    // alert(res.data.error_msg)
  }
  return res
}
export default {
  post (url, data) {
    return axios({
      method: 'post',
      baseURL: localhosts,
      // https://cnodejs.org/api/v1
      url,
      data: qs.stringify(data),
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
    get (url, params) {
    return axios({
      method: 'get',
      baseURL: localhosts,
      url,
      params, // get 请求时带的参数
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  }
}
写到这里http.js的内容也算是结束了。

下面还有就是api的一个封装了:

api.js

export default {
  right: '/dev/reverse', // 正确路径/topic/5433d5e4e737cbe96dcef312
  container:'/dev/history',
  error: '/topc/5433d5e4e737cbe96dcef312', // url错误
  backEnd: '/topic/5433d5e4e737cbe96dcef31' // 参数错误
}
这两个js写完一定要进行全局的配置,或者说到时那个组件需要就给他单独的引用也是可以的,我是直接将这个配置到全局里面去了为了方便下面是在main.js中的引入代码:

main.js

    import Vue from 'vue'
    import App from './App'
    import router from './router'
    import http from './utils/http'
    import api from './utils/api'


    Vue.prototype.http = http;
    Vue.prototype.api = api;

    Vue.config.productionTip = false;

    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      components: {App},
      template: '<App/>'
    });

一定要配置进去要不然没有效果的!!!!!!

下面的就是在项目中的引用了这玩意主要就是配合vue来进行开发的所以我就只上获取数据的代码了:

methods: {
  //获取接口
  fetchDatas: async function (currentIndex, pageName) {
    let params = {
      index: currentIndex,
      pagesize: pageName,
    };
    const res = await this.http.get(this.api.container, params);//获取成功
    if (res.status == 200) {
      this.getpage = res.data.data;
      this.pagedata = this.getpage.records;
      this.total = this.getpage.total;//拿到总条数
    } else {
      const dataError = await this.http.get(this.api.error, params);//获取失败
      if (dataError.status != 200) {
        console.info(dataError);
      }
    }
  }

在这里就可以把你的参数什么的直接放进去就可以调用了,到这里也就结束了!!

猜你喜欢

转载自blog.csdn.net/github_39088222/article/details/79717039