pc和uniapp,封装axios以及增删改查请求

//request.js
//PC端封装axios

import axios from 'axios'
import {ElMessageBox} from 'element-plus'
import urlJson from './../../public/config.json'
import router from '../router'

axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? urlJson.productUrl : urlJson.baseUrl;

axios.defaults.timeout = 20000; // 超时时间
axios.defaults.retry = 1;// 请求失败重试次数,共请求2次
axios.defaults.retryDelay = 1000;// 请求的间隙

// 添加请求拦截器
axios.interceptors.request.use((config) => {
        config.headers.common['AccessToken'] = sessionStorage.getItem('token')
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

let tokenInvalidFlag = 0;//token无效标志
// 添加响应拦截器
axios.interceptors.response.use(response => {
    switch (response.data.code) {
        case 200:
            tokenInvalidFlag = 0;
            break
        default:
    }
    return response
}, err => {
    //console.log(err.response)
    //避免登录失败还报504错
    if(err.response==undefined){
        return
    }
    if (err.response.config.url != '/getRouters') {
        switch (err.response.data.code) {
            // 504 token 过期
            case 504:
                if (tokenInvalidFlag === 0) {
                    tokenInvalidFlag = 1
                    sessionStorage.removeItem('token');
                    sessionStorage.removeItem('username');
                    ElMessageBox.alert(err.response.data.msg, '提示', {
                        confirmButtonText: '确定',
                        callback: action => {
                            router.replace({
                                path: '/login',
                                query: {
                                    redirect: router.currentRoute.value.fullPath
                                }
                            });
                        }
                    });
                }

                break
        }
    }

    return Promise.reject(err)
})

export {axios}

 

//request.js
//uniapp 封装axios

import axios from 'axios'

axios.defaults.baseURL = 'http://127.0.0.1:8888'
axios.defaults.timeout = 30000; // 超时时间

// request拦截器,在请求之前做一些处理
axios.interceptors.request.use(
	config => {
		config.headers.common['Authorization'] =uni.getStorageSync('token')
		return config;
	},
	error => {
		console.log(error); // for debug
		return Promise.reject(error);
	}
);

//配置成功后的拦截器
axios.interceptors.response.use(res => {
	return res
}, error => {
	return Promise.reject(error)
})

//uniapp适配axios,否则会报错:adapter is not a function
axios.defaults.adapter = function(config) {
  return new Promise((resolve, reject) => {
      //console.log(config)
      var settle = require('axios/lib/core/settle');
      var buildURL = require('axios/lib/helpers/buildURL');
      uni.request({
          method: config.method.toUpperCase(),
          url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
          header: config.headers,
          data: config.data,
          dataType: config.dataType,
          responseType: config.responseType,
          sslVerify: config.sslVerify,
          complete: function complete(response) {
              response = {
                  data: response.data,
                  status: response.statusCode,
                  errMsg: response.errMsg,
                  header: response.header,
                  config: config
              };

              settle(resolve, reject, response);
          }
      })
  })
}


export {
	axios
}
//http.js,uniapp同

import {axios} from './request'

// get 请求
const get = function (url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

// get-拼接参数的方式 ?param=''?
// {id:'123',te:'y'}
const getJoin = function (url, params) {
    let paramStr = url + '?'
    for (const k in params) {
        paramStr = paramStr + k + ':' + params[k] + '&'
    }
    paramStr = paramStr.replace(/:/g, '=')
    const paramArr = paramStr.split('')
    if (paramArr[paramArr.length - 1] === '&') {
        paramArr.pop()
    }
    const newParam = paramArr.join('')
    return new Promise((resolve, reject) => {
        axios.get(newParam)
            .then(res => {
                resolve(res)
            }).catch(err => {
            reject(err)
        })
    })
}

// POST 请求
const post = function (url, data) {
    //console.log(data, '测试http')
    return new Promise((resolve, reject) => {
        axios.post(url, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

// PUT 请求
const put = function (url, data) {
    return new Promise((resolve, reject) => {
        axios.put(url, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

// DELETE 请求
const del = function (url, data) {
    return new Promise((resolve, reject) => {
        axios.delete(url, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

//下载文件
const getFile = function (url,data) {
    return new Promise((resolve, reject) => {
        axios({
            url: url,
            responseType: "blob",
            method: 'get',
            params: data
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

//上传文件
const postUpload = function (url, data, params) {
    return new Promise((resolve, reject) => {
        axios({
            url: url,
            method: 'POST',
            headers: {
                'Content-type': 'multipart/form-data;boundary=${new Date().getTime()}',
            },
            data: data,
            params: params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

export default {get, post, put, del, getJoin, getFile, postUpload}

你可能感兴趣的:(js,前端)