美文网首页
vue axios封装

vue axios封装

作者: 肆意放纵 | 来源:发表于2019-07-25 16:38 被阅读0次

import axios from "axios";

import { Message }from "../../node_modules/element-ui";

import { MessageBox }from '../../node_modules/element-ui';

axios.defaults.withCredentials = true; //意思是携带cookie信息,保持session的一致性

axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset = UTF-8";

axios.defaults.headers.post["Accept"] = "application/json";

function onRespons(res) {

if (res.data.status === -1) {

    Message.error(res.data.msg);

}

if (!res.data.success) {

  if (res.data.code ===880104) {

      MessageBox.alert(res.data.msg, {

            confirmButtonText:'确定'

      }).then(() => {

            location.href = res.data.data;

            sessionStorage.clear();

      }).catch(() => {

            location.href = res.data.data;

            sessionStorage.clear();

      });

  }else {

            Message.error(res.data.msg);

  }

// Promise.reject(res);

//throw res;

    return res;

  } else {

    return res;

  }

}

function onError(error) {

if (error && error.response) {

switch (error.response.status) {

      case 400:

error.message ="请求错误";

        break;

      case 401:

error.message ="未授权,请登录";

        break;

      case 403:

error.message ="拒绝访问";

        break;

      case 404:

error.message =`请求地址出错: ${error.response.config.url}`;

        break;

      case 408:

error.message ="请求超时";

        break;

      case 500:

error.message ="服务器内部错误";

        break;

      case 501:

error.message ="服务未实现";

        break;

      case 502:

error.message ="网关错误";

        break;

      case 503:

error.message ="服务不可用";

        break;

      case 504:

error.message ="网关超时";

        break;

      case 505:

error.message ="HTTP版本不受支持";

        break;

      default:

error.message ="连接出错";

    }

}

// Do something with request error

  Message.error(error.message);

  // console.log(error); // for debug

// Promise.reject(error);

  throw error;

  // return error;

}

// create an axios instance

const apiService = axios.create({

// baseURL: '/service' // api的base_url

  baseURL:"/" // api的base_url

// timeout: 5000, // request timeout

});

apiService.interceptors.response.use(

res =>onRespons(res),

  error =>onError(error)

);

export default apiService;

相关文章

网友评论

      本文标题:vue axios封装

      本文链接:https://www.haomeiwen.com/subject/zbnhrctx.html