当前位置: 首页 > news >正文

Axios 底层 baseURL 拼接源码解析*

📌Axios 底层 baseURL 拼接源码解析

让我深入 Axios 源码,揭示 baseURL 拼接的底层实现机制:

🔍Axios 源码核心实现

1. 请求拦截核心 -dispatchRequest.js

// axios/lib/core/dispatchRequest.jsmodule.exports=functiondispatchRequest(config){// ⭐ 关键步骤:合并 baseURL 和 urlif(config.baseURL&&!isAbsoluteURL(config.url)){// 如果 url 不是绝对路径,就拼接 baseURLconfig.url=combineURLs(config.baseURL,config.url);}// 继续处理请求...returnadapter(config).then(...);}// 判断是否是绝对URLfunctionisAbsoluteURL(url){// 检查是否以协议开头(如 http://, https://)或以 // 开头return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);}// 拼接URL的工具函数functioncombineURLs(baseURL,relativeURL){// 去掉 baseURL 末尾的 '/' 和 relativeURL 开头的 '/'returnrelativeURL?baseURL.replace(/\/+$/,'')+'/'+relativeURL.replace(/^\/+/,''):baseURL;}

2. 实际执行流程

// 假设配置constconfig={baseURL:'http://localhost:8081/jeecg-boot/',url:'/sys/user/list'}// 步骤1:判断 url 是否是绝对路径isAbsoluteURL('/sys/user/list')// false,因为不以 http:// 或 // 开头// 步骤2:拼接 baseURL 和 urlcombineURLs('http://localhost:8081/jeecg-boot/','/sys/user/list')// 执行过程:// 1. baseURL.replace(/\/+$/, '') → 'http://localhost:8081/jeecg-boot'(去掉末尾斜杠)// 2. relativeURL.replace(/^\/+/, '') → 'sys/user/list'(去掉开头斜杠)// 3. 拼接结果:'http://localhost:8081/jeecg-boot' + '/' + 'sys/user/list'// 最终:'http://localhost:8081/jeecg-boot/sys/user/list'

🏗️完整的底层调用链

// 1. 用户调用axios.get('/sys/user/list')// 2. Axios.prototype.request (axios/lib/core/Axios.js)Axios.prototype.request=functionrequest(config){if(typeofconfig==='string'){config=arguments[1]||{};config.url=arguments[0];// 设置 url}config=mergeConfig(this.defaults,config);// 合并默认配置returndispatchRequest(config);// 调用 dispatchRequest}// 3. dispatchRequest (axios/lib/core/dispatchRequest.js)functiondispatchRequest(config){// ⭐ 核心拼接逻辑if(config.baseURL&&!isAbsoluteURL(config.url)){config.url=combineURLs(config.baseURL,config.url);}returnadapter(config);}// 4. adapter (axios/lib/adapters/xhr.js) - 实际发送请求functionxhrAdapter(config){returnnewPromise(function(resolve,reject){varrequest=newXMLHttpRequest();// ⭐ 最终请求地址就是拼接后的 config.urlrequest.open(config.method.toUpperCase(),config.url,true);// 发送请求...});}

📊URL 拼接的几种情况

情况1:相对路径拼接

// baseURL = 'http://localhost:8081/jeecg-boot'// url = '/sys/user/list'// 源码处理config.baseURL='http://localhost:8081/jeecg-boot'config.url='/sys/user/list'// 拼接结果config.url='http://localhost:8081/jeecg-boot/sys/user/list'

情况2:绝对路径不拼接

// baseURL = 'http://localhost:8081/jeecg-boot'// url = 'http://other-domain.com/api'isAbsoluteURL('http://other-domain.com/api')// true// 直接返回原 url,不拼接config.url='http://other-domain.com/api'

情况3:无 baseURL

// baseURL = undefined// url = '/sys/user/list'// 因为 config.baseURL 为 false,跳过拼接config.url='/sys/user/list'

🔧JeecgBoot 中的具体实现

1. 配置初始化

// src/utils/request.jsconstservice=axios.create({baseURL:window._CONFIG['domianURL']||'/jeecg-boot',// ⭐ 设置 baseURLtimeout:60000})// 这里的 baseURL 会被合并到每个请求的 config 中

2. 请求拦截器(可查看最终URL)

// src/utils/request.jsservice.interceptors.request.use(config=>{console.log('请求前URL:',config.url)console.log('baseURL:',config.baseURL)// 如果想查看最终拼接后的完整URLconstfullUrl=config.baseURL+config.url console.log('完整请求地址:',fullUrl)// 添加 token 等returnconfig})

3. 响应拦截器

service.interceptors.response.use(response=>{console.log('请求成功URL:',response.config.url)returnresponse.data})

🎯手动实现类似功能

// 自己实现一个简单的拼接函数classSimpleAxios{constructor(config){this.baseURL=config.baseURL||''}// 判断是否为绝对URLisAbsoluteURL(url){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url)}// 拼接URLcombineURLs(baseURL,relativeURL){if(!baseURL)returnrelativeURLif(this.isAbsoluteURL(relativeURL))returnrelativeURLreturnbaseURL.replace(/\/+$/,'')+'/'+relativeURL.replace(/^\/+/,'')}// 请求方法request(url,options={}){// 拼接 URLconstfinalUrl=this.combineURLs(this.baseURL,url)console.log('最终请求地址:',finalUrl)// 发送请求...returnfetch(finalUrl,options)}get(url){returnthis.request(url,{method:'GET'})}post(url,data){returnthis.request(url,{method:'POST',body:JSON.stringify(data)})}}// 使用示例constaxios=newSimpleAxios({baseURL:'http://localhost:8081/jeecg-boot'})axios.get('/sys/user/list')// 输出: 最终请求地址: http://localhost:8081/jeecg-boot/sys/user/list

📝源码关键点总结

  1. 判断条件if (config.baseURL && !isAbsoluteURL(config.url))

    • 必须有 baseURL
    • url 不能是绝对路径
  2. 拼接函数combineURLs(baseURL, relativeURL)

    • 处理多余的斜杠
    • 保证格式正确
  3. 执行时机:在dispatchRequest阶段

    • 所有拦截器执行之后
    • 实际发送请求之前
  4. 最终使用:adapter 中直接使用拼接后的config.url

这个设计让 axios 既保持了灵活性(支持绝对路径),又提供了便利性(自动拼接 baseURL)。

📌是的,axios 会自动拼接 baseURL!

这是 axios 的核心功能之一,让我详细解释:

🔧axios 的 baseURL 机制

1. 基本工作原理

importaxiosfrom'axios'// 创建 axios 实例时设置 baseURLconstservice=axios.create({baseURL:'http://localhost:8081/jeecg-boot',// 基础路径timeout:60000})// 请求时只需写相对路径service.get('/sys/user/list')// 实际请求: http://localhost:8081/jeecg-boot/sys/user/listservice.post('/sys/user/add',{username:'张三'})// 实际请求: http://localhost:8081/jeecg-boot/sys/user/addservice.put('/sys/user/edit',{id:1,status:1})// 实际请求: http://localhost:8081/jeecg-boot/sys/user/edit

📊拼接规则详解

规则1:相对路径自动拼接

// baseURL = http://localhost:8081/jeecg-boot// ✅ 相对路径(以 / 开头)- 会拼接service.get('/sys/user/list')// 结果: http://localhost:8081/jeecg-boot/sys/user/list// ✅ 相对路径(不以 / 开头)- 也会拼接service.get('sys/user/list')// 结果: http://localhost:8081/jeecg-boot/sys/user/list

规则2:绝对路径不拼接

// baseURL = http://localhost:8081/jeecg-boot// ❌ 绝对路径(包含 http://)- 不拼接service.get('http://other-domain.com/api/test')// 结果: http://other-domain.com/api/test(直接使用,不拼接 baseURL)// ❌ 绝对路径(以 // 开头)- 不拼接service.get('//other-domain.com/api/test')// 结果: //other-domain.com/api/test(不拼接)

🔍JeecgBoot 中的实际应用

1. request.js 中的配置

// src/utils/request.jsimportaxiosfrom'axios'// 从 window._CONFIG 获取 baseURLconstapiBaseUrl=window._CONFIG['domianURL']||'/jeecg-boot'// 创建 axios 实例,设置 baseURLconstservice=axios.create({baseURL:apiBaseUrl,// ⭐ 这里设置全局 baseURLtimeout:60000,withCredentials:true})exportdefaultservice

2. api/manage.js 中的使用

// src/api/manage.jsimportservicefrom'@/utils/request'// 封装的 GET 请求exportfunctiongetAction(url,params){returnservice({url:url,// 只需传相对路径method:'get',params})// service 会自动拼接 baseURL + url}// 封装的 POST 请求exportfunctionpostAction(url,data){returnservice({url:url,// 只需传相对路径method:'post',data})}// 封装的 PUT 请求exportfunctionputAction(url,data){returnservice({url:url,// 只需传相对路径method:'put',data})}

3. 在组件中使用

// UserList.vueimport{getAction,postAction,putAction}from'@/api/manage'exportdefault{methods:{// 查询列表loadData(){// 只需传相对路径,axios 自动拼接 baseURLgetAction('/sys/user/list',{pageNo:1,pageSize:10})// 实际请求: http://localhost:8081/jeecg-boot/sys/user/list},// 新增用户addUser(){postAction('/sys/user/add',{username:'张三'})// 实际请求: http://localhost:8081/jeecg-boot/sys/user/add},// 编辑用户editUser(){putAction('/sys/user/edit',{id:1,status:1})// 实际请求: http://localhost:8081/jeecg-boot/sys/user/edit}}}

🎯查看实际请求地址

在浏览器控制台查看

// 方法1:在 Network 标签查看// F12 → Network → 找到请求 → 查看 Request URL// 方法2:在代码中打印service.interceptors.request.use(config=>{console.log('最终请求地址:',config.baseURL+config.url)console.log('完整URL:',config.url)returnconfig})

实际输出示例

// 当 baseURL = http://localhost:8081/jeecg-boot// 请求 /sys/user/list 时最终请求地址:http://localhost:8081/jeecg-boot/sys/user/list

💡拼接的三种情况

请求的 URLbaseURL最终请求地址说明
/sys/user/listhttp://localhost:8081/jeecg-boothttp://localhost:8081/jeecg-boot/sys/user/list✅ 自动拼接
sys/user/listhttp://localhost:8081/jeecg-boothttp://localhost:8081/jeecg-boot/sys/user/list✅ 自动拼接
http://other.com/apihttp://localhost:8081/jeecg-boothttp://other.com/api❌ 不拼接(绝对路径)

⚠️注意事项

1. 不要重复拼接

// ❌ 错误:手动拼接了 baseURLconstfullUrl='http://localhost:8081/jeecg-boot/sys/user/list'getAction(fullUrl)// 结果会变成 http://localhost:8081/jeecg-boot/http://localhost:8081/jeecg-boot/sys/user/list// ✅ 正确:只需传相对路径getAction('/sys/user/list')

2. 处理带参数的 URL

// 带查询参数的 URLgetAction('/sys/user/list',{pageNo:1,pageSize:10})// 最终: http://localhost:8081/jeecg-boot/sys/user/list?pageNo=1&pageSize=10// 带路径参数的 URLputAction('/sys/user/edit/1',{status:1})// 最终: http://localhost:8081/jeecg-boot/sys/user/edit/1

3. 检查 baseURL 是否正确

// 在 request.js 中添加调试代码console.log('当前 baseURL:',apiBaseUrl)// 输出: 当前 baseURL: http://localhost:8081/jeecg-boot

📝总结

是的,axios 会自动拼接 baseURL!

  • 在 JeecgBoot 中,baseURL 在src/utils/request.js中设置
  • 组件中调用getAction('/sys/user/list')时,axios 会自动拼接成http://localhost:8081/jeecg-boot/sys/user/list
  • 这个机制让你只需写相对路径,简化了代码,便于切换不同环境的 API 地址
http://www.jsqmd.com/news/461039/

相关文章:

  • 真空助力器标准装配图CAD图纸
  • 立体车库的几种CAD图
  • CCP基本命令—种子获取、ECU解锁
  • 2026年靠谱的洗卸二合一洗面奶品牌推荐:洗卸二合一洗面奶销售厂家推荐 - 品牌宣传支持者
  • 数模混合芯片:Bug最爱藏在交界处
  • 芯片公司的尴尬真相:连软件工程1.0都没做到
  • 养虾实战教程:我用OpenClaw做了个能盯盘,也能深度复盘的投资agent
  • Gmc设置满50$运费促销点击次数增长2130%、展示次数增长215%、点击率增长607%
  • 数据团队新死法:不是做得差,是做得“够用“
  • 外包员工“工具化”:当职场人沦为可替换的“零件”
  • google merchant center(Gmc) 配送和退货 实现美国仓单品满足50$在SERP页面免运费
  • 【MySQL数据库】--借助AI快速画数据库ER图
  • 【数据库】--PostgreSQL 详细安装教程
  • Flutter 三方库 growth_standards 的鸿蒙化适配指南 - 实现标准化的儿童生长曲线计算、支持 WHO 规范与健康管理数据可视化
  • Flutter 三方库 fast_base 的鸿蒙化适配指南 - 实现极速的基础架构搭建、支持响应式 Repository 封装与业务模型注入
  • 【精度】【核内同步】applyTopKTopPWithSorted算子精度问题定位
  • Pytorch2 PyTorch 张量(Tensors)完全指南
  • PyTorch4 Transforms 保姆级教程|ToTensor Lambda 实战
  • PyTorch5 构建神经网络保姆级教程|从层到模型全拆解
  • 2026年质量好的混纺PTFE滤袋厂家推荐:混纺PTFE滤袋厂家选择指南 - 品牌宣传支持者
  • C++ Lambda表达式:高效编程利器
  • C++进阶:从C到C++的完美过渡
  • 2026年口碑好的PTFE滤袋公司推荐:针刺毡PTFE滤袋实力厂家推荐 - 品牌宣传支持者
  • 宝鸡钛棒源头厂家/宝鸡钛棒现货工厂怎么挑?2026宝鸡钛合金棒厂家推荐:宝鸡鹰翔钛业,源头厂家实力供应 - 栗子测评
  • 精选2026宝鸡纯钛棒厂家推荐/TC4钛棒生产厂家推荐:宝鸡鹰翔钛业生产厂家直供 - 栗子测评
  • 精选2026甲基丙基酰氧基硅烷供应商/烷基硅烷生产厂家:杭州杰西卡,源头直供与定制化方案 - 栗子测评
  • “现代战争”天梯赛习题
  • 2026纳米二氧化钛厂家|二氧化钛分散液源头厂家-优选宁波极微纳 - 栗子测评
  • Flutter 三方库 commander_ui 的鸿蒙化适配指南 - 构建大屏控制台风格 UI、支持指令式交互与极客风格面板
  • 宿舍管理系统厂家怎么选?2026学生宿舍管理系统推荐:掌门物联科技-创新校园住宿管理智能化新体验 - 栗子测评