当axios发送请求需要自定义baseURL路径

368 阅读2分钟
话不多说直接上正文
  1. 第一步下载安装axios,相信大家都会
pnpm i axios
import axios from 'axios'

2.第二步创建实例

const service = axios.create({
  //基础请求地址
  baseURL:process.env.VITE_APP_MODE === 'production' ? '开发环境请求地址' : '生产环境请求地址', 
  timeout: 5000 
})
 //关键在请求拦截器中修改
service.interceptors.request.use(
  (config) => {
    // 如果传入了mybaseURL,则使用传入的mybaseURL,否则使用默认的baseURL
    if(config.mybaseURL){
      service.defaults.baseURL = config.mybaseURL
      config.baseURL = config.mybaseURL
    }else{
      service.defaults.baseURL = baseURL
      config.baseURL = baseURL
    }
    // 处理application/x-www-form-urlencoded参数
    if (config.headers && config.headers.mytype === 'formdata') {
      if (!(config.data instanceof FormData)) {
        config.transformRequest = function (obj) {
          var str = []
          for (var p in obj) {
            if (Array.isArray(obj[p])) {
              for (var i = 0; i < obj[p].length; i++) {
                str.push(encodeURIComponent(p + '[' + i + ']') + '=' + encodeURIComponent(obj[p][i]))
              }
            } else if (typeof obj[p] === 'object' && obj[p] !== null) {
              // 递归处理嵌套对象
              var nestedStr = []
              for (var key in obj[p]) {
                nestedStr.push(encodeURIComponent(p + '[' + key + ']') + '=' + encodeURIComponent(obj[p][key]))
              }
              str = str.concat(nestedStr)
            } else {
              str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
            }
          }
          return str.join('&')
        }
        config.headers = {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    }
    // ... 其他逻辑
    if (config.reqLoading ?? true) {
      loadingInstance = ElLoading.service({
        lock: true,
        fullscreen: true,
        text: ' ',
        background: 'rgba(0, 0, 0, 0.1)'
      })
    }
    // 加入token
    const { token } = useBasicStore()
    if (token) config.headers['Authorization'] = 'Bearer ' + token
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
//响应拦截器
service.interceptors.response.use(
  (response) => {
    // 如果有loading实例,关闭loading
    if (loadingInstance) {
      loadingInstance && loadingInstance.close()
    }
    const res = response.data
    if ((res.status && res.status !== 200 || res.success && res.success === false) || (res.code && res.code !== 0)) {
      ElMessage({
        message: res.msg || 'Error',
        type: 'error',
        plain: true,
        duration: 5 * 1000
      })
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.status === 50008 || res.status === 50012 || res.status === 50014) {
        // to re-login
        ElMessageBox.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'
          }
        )
      }
      return Promise.resolve(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    // 如果有loading实例,关闭loading
    if (loadingInstance) {
      loadingInstance && loadingInstance.close()
    }
    let msg = error.response?.data?.msg || error.message
    ElMessage({
      message: msg,
      type: 'error',
      plain: true,
      duration: 5 * 1000
    })
    return Promise.resolve(error)
  }
)
//导出
export default service
  1. 使用方式
//导入文件
import request from '../utils/req.js'
//一、发送json参数格式的请求
export function InsertTeam(data) {
  return request({
    url: '/api/zhaiquan/InsertTeam',
    method: 'post',
    data,
  })
}
//二、发送query查询字符串格式请求参数
export function preConnect(params) {
  return request({
    url: '/api/v1/preConnect',
    method: 'get',
    params,
  })
}
//三、发送application/x-www-form-urlencoded格式参数
export function AiOperaDebt(data) {
  return request({
    url: '/api/zhaiquan/AiOperaDebt',
    method: 'post',
    data,
    headers: { mytype: 'formdata'}
  })
}
//四、自定义baseURL
export function GetIndexChatData(params) {
  return request({
    url: '/api/v1/GetIndexChatData',
    method: 'get',
    params,
    reqLoading:true,//是否需要加载loading(全局)
    mybaseURL:'https://baidu.com'//这里写需要更改的请求地址
  })
}

5.效果

image.png 此时发现正常的接口地址请求正常,自定义的请求地址请求失败,因为压根没有!