Vue封装axios 请求接口

request.js

/*
 * @Description:
 * @Author: Nan
 * @Date: 2021-04-15 09:24:13
 * @LastEditors: nanJ
 * @LastEditTime: 2021-09-17 15:20:28
 * @FilePath: \architect-rating-web\src\utils\request.js
 */
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      config.headers['Authorization'] = `${getToken()}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.success != 1) {
      Message({
        message: res.msg || res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 401) {
        // to re-login
        MessageBox.confirm('登录到期,请重新登录!', '提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '关闭',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.msg || res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    if (error.response.data.msg == '登录信息失效,请重新登录!') {
      MessageBox.confirm('登录到期,请重新登录!', '提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '关闭',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    } else {
      console.log('err' + error) // for debug
      Message({
        message: error.response.data.msg || error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }

    return Promise.reject(error)
  }
)

export default service

 应用

export function saveFile(params) {
  return request({
    url: '/project/bid/add',
    method: 'post',
    data: params
  })
}

  

/**
 * Template
 * created by qiangxu on 2021/3/10
 */

declare const baseURL: string;
import axios from "axios";
import {Message} from "element-ui";

axios.interceptors.request.use(config => {
  config.baseURL = config.baseURL===undefined?baseURL:config.baseURL;
  config.validateStatus = () => true;
  return config
});

export class DataService {
  static async ajax(_type: "get" | "delete" | "head" | "options" | "post" | "put" | "patch", url: string, _params = {}, _options = {}) {
    try {
      const response = await (axios as any)[_type](url, _params, _options);
      if (response.status === 500) {
        throw response
      }
      if (response.data.success) {
        return response.data;
      }
      return response.data;
    }
    catch (response) {
      let error;
      if (response.status === 0) {
        error = "连接出错,请确认网络是否正常";
      }
      else {
        error = response.data && response.data.errMsg || response;
      }
      Message.error(response.data.errMsg)
      throw new Error(error);
    }
  }

  static async get(url: string, _params = {}, _options = {}) {
    return await this.ajax("get", url, {params: _params, ..._options});
  }

  static async post(url: string, _params = {}, _options = {}) {
    return await this.ajax("post", url, _params, _options);
  }

  static async delete(url: string, _params = {}, _options = {}) {
    return await this.ajax("delete", url, _params, _options);
  }
}

  

 async getData(id: Number) {
      let url = `/LDJSSB/GetEntityById?id=${id}`;
      return DataService.get(url);
},

  

posted @ 2021-11-04 14:08  闰土的土  阅读(305)  评论(0编辑  收藏  举报