axios请求封装(自用)

发布于 2023-08-29  102 次阅读


普通请求封装

import axios from "axios";
import Vue from 'vue'

import CryptoJS from 'crypto-js'
import router from "@/router";
import store from "@/store";
import {
    Message
} from 'element-ui';

// import {
//     writeApi
// } from "./api"

//外网http://8.134.122.251
//测试内网 http://192.168.221.62

// var xhr = new XMLHttpRequest();

// xhr.onreadystatechange = function () {
//     alert(xhr.status)
//     console.log(xhr);
// }

// xhr.open('get', 'http://8.134.122.251/config.json', true)
// xhr.send();

// http://8.134.122.251/fg-service1
// http://8.134.122.251  外网
//http://192.168.221.62  内网
//http://192.168.168.241:8081/fg-service 官网

// 专网地址http://192.168.0.232/fg-service
let baseApi = localStorage.getItem("baseApi") || 'none'
let port = localStorage.getItem("port") || '80'

let apis = {
    //外网线上
    // production: 'http://8.134.122.251/fg-service', //  (生成环境)
    //内网线上
    // production: 'http://192.168.221.62/fg-service', //(生成环境)
    // production: 'http://192.168.0.232/fg-service',
    production: 'http://' + baseApi + ':' + port + '/fg-service', //(生成环境)

    // production: 'http://192.168.168.244/fg-service',

    // production: 'http://192.168.221.36:8081/fg-service', //(生成环境)
    //专网环境
    // production: 'http://192.168.221.62/fg-service', //(生成环境)
    development: '/fg-service', //  (开发环境)
}

//提示次数
let timeoutCont = 1;

// 
//测试服
// env
// http://8.134.122.251/fg-service
const instance2 = axios.create({
    baseURL: process.env.NODE_ENV === 'production' ? apis.production : apis.development,
    // baseURL: "http://192.168.221.62/fg-service",
    timeout: 5000,
    withCredentials: false,

})
//外网 http://8.134.122.251/
//内网 http://192.168.221.62/fg-service

instance2.interceptors.request.use(config => {

        const token = localStorage.getItem('token')
        let timestamp = new Date().getTime()
        let timestamp_str = CryptoJS.MD5(timestamp + "").toString()
        if ((window.location.href.includes("login") == false) && (window.location.href[window.location.href.length - 1] != "/")) {
            if (token) {
                config.headers = config.headers || {}

                config.headers['Authorization'] = "Bearer " + token
                config.headers["timestampDesc"] = timestamp_str
                config.headers["timestamp"] = timestamp + ""

            }
        }

        config.headers["language"] = store.state.isChinese ? "" : "en_US"

        // alert("noen")

        // else {

        //     config.headers["timestampDesc"] = timestamp_str
        //     config.headers["timestamp"] = timestamp + ""
        // }

        return config
    },
    // err => Promise.reject(err)
)

// router.app._route.name有方法修复了,回来再修

// 响应拦截
instance2.interceptors.response.use(config => {
    console.log(config.data.code);
    //mqtt版本废弃

    if (config.data.code != 0) {
        // alert(1)
        // console.log("config.data");
        // console.log(config.data.message);
        Message.warning(config.data.message)
    }

    // if (config.data.code == -1) {

    //     if (router.app._route.name != 'Login') {
    //         if (sessionStorage.getItem("login") == 1) {
    //             alert("This account has already logged in on another device!")
    //             sessionStorage.setItem("login", 0);
    //         }
    //         // timeoutCont = 1

    //         router.push('/login')

    //     }

    // }

    return config

}, err => {
    console.log("-----------");

    if (timeoutCont == 1) {
        if (router.app._route.name == 'Login') {
            if (err.message.includes('timeout')) {
                //如果是登录接口才会弹
                if (err.config.url == "/token/getToken") {
                    //一次性提醒请求超时
                    alert(store.state.isChinese ? "请求超时" : "request timeout")
                    timeoutCont--
                }

            }
        }

    }

    // Promise.reject(err)
})

export {
    apis
}
export default instance2

请求头为form-data

import axios from "axios";
import Vue from 'vue'

import CryptoJS from 'crypto-js'
import router from "@/router";

// import {
//     writeApi
// } from "./api"

//外网http://8.134.122.251
//测试内网 http://192.168.221.62

// var xhr = new XMLHttpRequest();

// xhr.onreadystatechange = function () {
//     alert(xhr.status)
//     console.log(xhr);
// }

// xhr.open('get', 'http://8.134.122.251/config.json', true)
// xhr.send();

// http://8.134.122.251/fg-service1
// http://8.134.122.251  外网
//http://192.168.221.62  内网
//http://192.168.168.241:8081/fg-service 官网
let baseApi = localStorage.getItem("baseApi") || 'none'
let port = localStorage.getItem("port") || '80'

let apis = {
    //外网线上
    // production: 'http://8.134.122.251/fg-service', //  (生成环境)
    //内网线上
    // production: 'http://192.168.221.62/fg-service', //(生成环境)
    // production: 'http://192.168.0.232/fg-service',
    production: 'http://' + baseApi + ':' + port + '/fg-service', //(生成环境)

    // production: 'http://192.168.221.62/fg-service',
    // production: 'http://192.168.168.244/fg-service',

    // production: 'http://192.168.221.36:8081/fg-service', //(生成环境)
    //专网环境
    // production: 'http://192.168.221.62/fg-service', //(生成环境)
    development: '/fg-service', //  (开发环境)
}

// 
//测试服
// env
// http://8.134.122.251/fg-service
const instance3 = axios.create({
    baseURL: process.env.NODE_ENV === 'production' ? apis.production : apis.development,
    // baseURL: "http://192.168.221.62/fg-service",
    timeout: 5000,
    withCredentials: false,

})
//外网 http://8.134.122.251/
//内网 http://192.168.221.62/fg-service

instance3.interceptors.request.use(config => {

        const token = localStorage.getItem('token')
        let timestamp = new Date().getTime()
        let timestamp_str = CryptoJS.MD5(timestamp + "").toString()
        if ((window.location.href.includes("login") == false) && (window.location.href[window.location.href.length - 1] != "/")) {
            if (token) {
                config.headers = config.headers || {}

                config.headers['Authorization'] = "Bearer " + token
                config.headers["timestampDesc"] = timestamp_str
                config.headers["timestamp"] = timestamp + ""
            }
        }
        config.headers["language"] = "en_US"
        config.headers["Content-Type"] = "multipart/form-data"

        // else {

        //     config.headers["timestampDesc"] = timestamp_str
        //     config.headers["timestamp"] = timestamp + ""
        // }

        return config
    },
    // err => Promise.reject(err)
)

// router.app._route.name有方法修复了,回来再修

// 响应拦截
instance3.interceptors.response.use(config => {
    console.log(config.data.code);
    if (config.data.code == -1) {
        // let bootConnect = JSON.parse(localStorage.getItem("bootConnect"));
        // writeApi({
        //     ...obj
        // }).then(res => {
        //     console.log("----------写入指令到船------");
        //     console.log(res);
        // });
        //账号在其他地方登录
        alert("This account has already logged in on another device!")

        router.push('/login')
    }
    return config

})

export default instance3

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。