VUE 请求api的封装

1.常用封装一(跟element-admin相同)

* 1.1在脚手架目录utils目录新建一个request.js 文件
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
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: 300000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = 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.code !== '0000') {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      if (res.code === '0002') {
        store.dispatch('user/resetToken').then(() => {
          // location.reload()
          store.dispatch('user/logout')
          router.push('/')
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
1.2 新建一个接口(api)目录把每个模块放到一个请求js文件里,引用封装的request.js
import request from '@/utils/request'
// 货权转移 插入
// business/ecargorightchange/{version}/insert
export function insertEcargorightchange(data) {
  return request({
    url: `/business/ecargorightchange/${version}/insert`,
    method: 'post',
    data: data
  })
}
// 货权转移  更新
// api/business/ecargorightchange/{version}/update
export function upDateEcargorightchange(data) {
  return request({
    url: `/business/ecargorightchange/${version}/update`,
    method: 'put',
    data: data
  })
}
// 根据ID 查询货权转移
// business/ecargorightchange/123/querybyid?id=123123
export function getEcargorightchangeByid(data) {
  return request({
    url: `/business/ecargorightchange/${version}/querybyid`,
    method: 'get',
    params: data
  })
}

2.常用封装二

2.1首先,建立一个request.js文件,引入axios,可以在该文件中,前端做请求拦截相应、请求方式统一处理
  • 安装 cnpm install axios --save
2.2接下来,创建axios实例
import axios from "axios"; //导入axios
export function request(config) {
    const instance = axios.create({
        baseURL: process.env.BASE_URL, // api base_url,
        timeout: 60 * 1000, // 请求超时时间,
        headers: { "Content-Type": "application/json" }, //请求头
    });

    // 1.axios 拦截器

    // 1.1请求拦截
    instance.interceptors.request.use(config => {
        return config
    }, err => {
        console.log(err)
    })

    //1.2响应拦截

    instance.interceptors.response.use(res => {
        return res.data
    }, err => {
        console.log(err)
    })

    // 1.3发送网络请求
    return instance(config)

}

2.3 引入上面这个文件
import request from '@/utils/request'
// 货权转移 插入
// business/ecargorightchange/{version}/insert
export function insertEcargorightchange(data) {
  return request({
    url: `/business/ecargorightchange/${version}/insert`,
    method: 'post',
    data: data
  })
}

二.案例

案例一:响应拦截器异常状态码处理

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    // 服务器状态码不是200的情况
    error => {
        if (error.response.status) {
            switch (error.response.status) {
                // 401: 未登录
                // 未登录则跳转登录页面,并携带当前页面的路径
                // 在登录成功后返回当前页面,这一步需要在登录页操作。
                case 401:
                    notification.error({
                        message: "请求失败",
                        description: "登录过期,请重新登录"
                    });
                    axios.get('/relog').then(() => {
                        location.href = window.location.origin 
                    })
                    break;
                // 403 token过期
                // 登录过期对用户进行提示
                // 清除本地token和清空vuex中token对象
                // 跳转登录页面
                case 403:
                    notification.error({
                        message: "请求失败",
                        description: "登录过期,请重新登录"
                    });
                    break;
                // 404请求不存在
                case 404:
                    notification.error({
                        message: "请求失败",
                        description: "网络请求不存在"
                    });
                    break;
                // 其他错误,直接抛出错误提示
                default:
                    notification.error({
                        message: "请求失败",
                        description: error.response.data.message
                    });
            }
            return Promise.reject(error.response);
        }
    }
);

案例二:分别对四种请求方式进行封装:url就是请求后端的地址,params是前端传给后端的参数

image

推荐阅读更多精彩内容