vue接口api封装

264 阅读2分钟

目录结构

image.png

配置代理

需要注意vue.config.js文件需要自己添加

devServer: {
    port: 201,
    proxy: { // 设置代理
        '/devapi': {
            target: 'http://192.168.100.78:8887', // 开发
            // target: 'http://backmaster.comewonka.com:8887',
            changeOrigin: true, // 是否允许跨域
            pathRewrite: { // 重写路径 
                '^/devapi': ''
            }
        },
        '/api': {
            target: 'http://aaa:8887/service-organiza', //测试
            // target: 'http://bbb:8887/service-organiza', //服务器
            changeOrigin: true,
            pathRewrite: { // 重写路径
                '^/api': ''
            }
        },
    },
},

封装axios

import axios from 'axios' //这里引用了element的loading全屏加载

import { Loading, Message } from "element-ui"

axios.defaults.withCredentials = true

const service = axios.create({ // baseURL: '/devapi', timeout: 30000 })

let loading = ""

// 请求拦截器

service.interceptors.request.use(

(config) => {
    // const token = document.cookie.split(';')[0].includes('EMS_TOKEN')
    //从登录页存入,在这里取出
    
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    // if (!token) {
    //     // config.headers['Authorization'] = token
    //     //config.headers['EMS_TOKEN'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjUyMDYxMDQ0NjUsImlkIjoxMTExMTExMTExfQ.ItErVYsQf9qykmiT-wyK2DEVQd3H7FljN8MuzoZuISc'      
    //     Message({
    //         message: "token状态异常",
    //         type: 'error'
    //     });
    //     process.env.NODE_ENV == "development" ? window.location.href = 'http://192.168.100.17:666/ ' : window.location.href = 'http://frontmaster.comewonka.com:666/login'
    //     return
    // }
    // 在请求发送之前做一些处理
    
    if (!(config.headers['Content-Type'])) {
    
        loading = Loading.service({
            lock: true,
            text: "加载中...",
            spinner: "el-icon-loading",
            background: "rgba(255,255,255,0.7)",
            customClass: "request-loading",
        })
        
        if (config.method == 'post' && config.type == 'upload') {
            config.headers['Content-Type'] = 'multipart/form-data'
        } else if (config.method == 'post' && config.type == 'download') {
            // 导出csv文件
            config.headers['Content-Type'] = 'application/json;charset=UTF-8'
            config.responseType = 'blob'
        } else if (config.method == 'post') {
                // config.headers['Content-Type'] = 'multipart/form-data'
                config.headers['Content-Type'] =
                    'application/json;charset=UTF-8'
                for (var key in config.data) {
                    if (config.data[key] === '') {
                        delete config.data[key]
                    }
                }
                config.data = JSON.stringify(config.data)
            } else {
                config.headers['Content-Type'] =
                    'application/x-www-form-urlencoded;charset=UTF-8'
                config.data = JSON.stringify(config.data)
            }
    }
    return config
},

(error) => {
    loading.close();
    // 发送失败
    console.log(666, error)
    return Promise.resolve(error)
}

)

// 响应拦截器 service.interceptors.response.use(

(response) => {
    loading.close()
    // const dataAxios = response
    // dataAxios 是 axios 返回数据中的 data
    if (response.config.type == 'download') {
        return response
    } else {
        const dataAxios = response.data
        // 这个状态码是和后端约定的
        if (dataAxios.code == 500) {
            Message.closeAll();
            Message({
                message: dataAxios.msg,
                type: 'error'
            });
        }
        return dataAxios
    }
}

error => {

    loading.close();
    if (error.response.status == 401) {
       window.location.origin + '/login'
        localStorage.clear()
        // 过期清除cookie
        let keys = document.cookie.match(/[^ =;]+(?==)/g)
        if (keys) {
            for (let i = keys.length; i--;) {
                document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString() // 清除当前域名下的,例如:m.ratingdog.cn
                document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString() // 清除当前域名下的,例如 .m.ratingdog.cn
                document.cookie = keys[i] + '=0;path=/;domain=ratingdog.cn;expires=' + new Date(0).toUTCString() // 清除一级域名下的或指定的,例如 .ratingdog.cn
            }
        }
    }
    return Promise.reject(error)
}    

)

export default service

api封装

// 引入封装好的axios

image.png import axios from "./request"

// 登出

export const logout = (params) => { return axios.get(loginapi + '/ums/login/logout') }

页面引用

// 引入封装好的接口

import { logout } from "@/api/api.js";

async getSelectproductGroupAddList() {
  let res = await logout({});
  if (res && res.code == 200) {
    this.ProductGroupAddList = res.data;
  }
},