欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue中axios请求的封装

程序员文章站 2022-07-03 17:48:43
创建utils文件夹安装axios$ npm install axios -S引入如下两个文件1.axios.jsconst VueAxios = { vm: {}, // eslint-disable-next-line no-unused-vars install(Vue, instance) { if (this.installed) { return; } this.installed = true;...

创建utils文件夹

安装axios

$ npm install axios -S

引入如下两个文件
1.axios.js

const VueAxios = {
    vm: {},
    // eslint-disable-next-line no-unused-vars
    install(Vue, instance) {
      if (this.installed) {
        return;
      }
      this.installed = true;
  
      if (!instance) {
        // eslint-disable-next-line no-console
        console.error("You have to install axios");
        return;
      }
  
      Vue.axios = instance;
  
      Object.defineProperties(Vue.prototype, {
        axios: {
          get: function get() {
            return instance;
          }
        },
        $http: {
          get: function get() {
            return instance;
          }
        }
      });
    }
  };
  
  export { VueAxios };

2.引入request.js文件

import axios from "axios";
import { VueAxios } from "./axios";
// import qs from "qs";  //需安装,按需引入
// 创建 axios 实例
/* eslint-disable */
const service = axios.create({
  baseURL:'http://192.168.199.195:8080',  //请求地址公共部分
  timeout: 6000, // 请求超时时间
  withCredentials: true,   //配置跨域
  // transformRequest: [
  //   function(data) {
  //     // 允许向服务器发送前,修改稿请求数据
  //     return qs.stringify(data); // 对data进行转换
  //   }
  // ]
});

const err = error => {   //响应异常拦截
  if (error.response) {
    const token = window.localStorage.getItem("token");
    if (error.response.status === 403) {
    		...
    }
    if (error.response.status === 401) {  //!(data.result && data.result.isLogin)
      if (token) {
        	window.localStorage.removeItem("token");
      }else{
       		....
      }
    }
  }
  return Promise.reject(error);
};

// request interceptor
service.interceptors.request.use(config => {   //请求拦截
  const token = window.localStorage.getItem("token");
  if (token) {
    config.headers["Authorization"] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config;
}, err);

// response interceptor
service.interceptors.response.use(response => {   //响应拦截
  return response.data;
}, err)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service);
  }
};

export { installer as VueAxios, service as axios };

本文地址:https://blog.csdn.net/hyy4668/article/details/107509274

相关标签: vue